【发布时间】:2021-03-19 15:57:50
【问题描述】:
我的 Java 类如下所示。这是一个测试线程加入(等待)和线程睡眠(定时等待)的小练习。
public class BasicThreadTest {
public static void main(String[] args) {
testThreadWait();
System.out.println(Thread.currentThread().getName() + " exiting");
}
private static void testThreadWait() {
Thread thread1 = new Thread(() -> {
String currentThread = Thread.currentThread().getName();
System.out.println(String.format("%s execution started", currentThread));
long waitMillis = 20000L;
try {
System.out.println(String.format("%s going for timed wait of %d millis", currentThread, waitMillis));
Thread.sleep(waitMillis);
} catch (InterruptedException e) {
System.out.println(String.format("%s timed wait over after %d millis", currentThread, waitMillis));
}
System.out.println(String.format("%s execution ending", currentThread));
});
thread1.setName("Thread-1");
Thread thread2 = new Thread(() -> {
String currentThread = Thread.currentThread().getName();
System.out.println(String.format("%s execution started", currentThread));
try {
System.out.println(currentThread + " about to wait for " + thread1.getName());
thread1.join();
} catch (InterruptedException e) {
System.out.println(String.format("%s wait over for %s", currentThread, thread1.getName()));
}
System.out.println(String.format("%s execution ending", currentThread));
});
thread2.setName("Thread-2");
thread2.start();
thread1.start();
}
}
无论我以什么顺序启动两个线程,我都不会在sleep() 或join() 中执行两个InterruptedException 块。下面是一个示例输出:
Thread-2 execution started
Thread-2 about to wait for Thread-1
main exiting
Thread-1 execution started
Thread-1 going for timed wait of 20000 millis
Thread-1 execution ending
Thread-2 execution ending
有什么解释为什么会这样吗?
【问题讨论】:
-
你在哪里中断线程?如果您不真正打断他们,您将不会收到
InterruptedException。 -
有道理,我曾假设一旦等待或定时等待结束,
InterruptedException总是会被抛出。情况并非如此,看起来必须明确调用interrupt()。
标签: java multithreading interrupted-exception