Java多线程wait-notify场景下Thread.join(1)未触发预期异常问题咨询
问题核心原因
你对Thread.join(long millis)方法的异常触发规则存在误解,该方法的InterruptedException并不是在等待超时的时候抛出的:
- 只有调用
join方法的线程(此处是main线程)被其他线程主动调用interrupt()中断时,才会抛出InterruptedException - 等待指定时长后超时属于方法的正常返回场景,不会抛出任何异常,会直接继续执行后续代码,因此不会走到你写的catch块中打印"exception"。
补充验证
如果你想要测试触发该异常,可以主动中断main线程,示例修改如下:
public static void main(String[] args) { // 提前保存main线程的引用 Thread mainThread = Thread.currentThread(); Handler handler = new Handler(); Thread thread1 = new Thread(() -> { try { handler.producer(); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread thread2 = new Thread(() -> { try { handler.consumer(); } catch (InterruptedException e) { e.printStackTrace(); } }); thread1.start(); thread2.start(); // 新增线程,用于中断main线程 new Thread(() -> { try { Thread.sleep(10); mainThread.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); try { thread1.join(1); thread2.join(1); } catch (InterruptedException e) { System.out.println("exception"); } }
运行修改后的代码就可以看到"exception"正常打印。
内容的提问来源于stack exchange,提问作者Bohdan Myslyvchuk
相关产品推荐
相关产品推荐

