java - Java线程InterruptedException块未执行
问题描述
下面给出了我的 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();
}
}
无论我以什么顺序启动两个线程,我都不会在或InterruptedException
中执行两个块。下面是一个示例输出:sleep()
join()
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
关于为什么会发生这种情况的任何解释?
解决方案
wait()
InterruptedException
当块(或等待)完成时不抛出。
如果您启动第三个调用的线程,thread1.interrupt()
那么您将获得InterruptedException
.
推荐阅读
- javascript - 将 URl 添加到 cookie 并在返回时重定向到 URL
- graphics - (GLSL)一个周末的光线追踪,如何将景深添加到视图矩阵?
- svelte - 有没有办法在 Sapper 路由中延迟加载动态导入?
- python-3.x - 什么是 KeyError:“twoColumnSearchResultsRenderer”(Python、youtube_dl)
- autohotkey - 将 gui 停靠到可变的活动窗口
- r - 将变量添加到 R 中的数据框并按所述变量排序
- reactjs - 如何在 ReactJs 中获取设备唯一 ID
- html - CSS/HTML:悬停图像,动画文本不起作用
- blazor - 当我有注册类型时,没有类型错误的注册服务
- node.js - nodejs 无法使用自动标头执行 http post