一个线程可以中断另一个线程吗?
Can one thread interrupts another thread?
我想知道在第一个线程的 运行 方法中中断另一个线程是否非法。如果是,当我在第一个线程的 运行 方法中调用另一个线程的中断方法时,会抛出 "InterruptedException" 吗?像这样:
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
while (true) {
}
}, "thread1");
try {
thread1.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Oops! I'm interrupted!");
}
Thread thread2 = new Thread(() -> {
System.out.println("I will interrupt thread1!");
thread1.interrupt();
System.out.println("Thread1 interruption done!");
}, "thread2");
thread1.start();
thread2.start();
}
但是我在控制台中没有收到消息 "Oops! I'm interrupted!"。
你的程序不工作的原因是你正在使用thread1
引用来访问静态sleep()
方法,但是睡眠仍然在主线程中执行。
将它移到 thread1
的正文中,您的程序工作正常:
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Oops! I'm interrupted!");
}
}, "thread1");
Thread thread2 = new Thread(() -> {
System.out.println("I will interrupt thread1!");
thread1.interrupt();
System.out.println("Thread1 interruption done!");
}, "thread2");
thread1.start();
thread2.start();
}
这会打印:
I will interrupt thread1!
Thread1 interruption done!
Oops! I'm interrupted!
请注意,最后两个打印输出的顺序取决于线程调度,并且可能会有所不同。
我想知道在第一个线程的 运行 方法中中断另一个线程是否非法。如果是,当我在第一个线程的 运行 方法中调用另一个线程的中断方法时,会抛出 "InterruptedException" 吗?像这样:
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
while (true) {
}
}, "thread1");
try {
thread1.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Oops! I'm interrupted!");
}
Thread thread2 = new Thread(() -> {
System.out.println("I will interrupt thread1!");
thread1.interrupt();
System.out.println("Thread1 interruption done!");
}, "thread2");
thread1.start();
thread2.start();
}
但是我在控制台中没有收到消息 "Oops! I'm interrupted!"。
你的程序不工作的原因是你正在使用thread1
引用来访问静态sleep()
方法,但是睡眠仍然在主线程中执行。
将它移到 thread1
的正文中,您的程序工作正常:
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Oops! I'm interrupted!");
}
}, "thread1");
Thread thread2 = new Thread(() -> {
System.out.println("I will interrupt thread1!");
thread1.interrupt();
System.out.println("Thread1 interruption done!");
}, "thread2");
thread1.start();
thread2.start();
}
这会打印:
I will interrupt thread1!
Thread1 interruption done!
Oops! I'm interrupted!
请注意,最后两个打印输出的顺序取决于线程调度,并且可能会有所不同。