InterruptedException:Thread#sleep如何响应线程中断?
线程中断与阻塞状态的处理逻辑
核心结论
当线程处于sleep()、wait()、join()这类阻塞状态时,调用其interrupt()方法会直接触发InterruptedException,同时清除线程的中断标志位,而非仅设置标志。
详细解释
运行中线程的中断处理
对于正在运行的线程,interrupt()仅会设置线程的中断标志位,线程需要主动通过以下方式感知中断:- 调用
Thread.currentThread().isInterrupted()检查标志位 - 调用会响应中断的阻塞方法(如
sleep()、wait()),此时方法会检测到中断标志并抛出InterruptedException
- 调用
阻塞状态线程的中断处理
当线程处于sleep()、wait()、join()等阻塞状态时,interrupt()的处理逻辑不同:- JVM会立即唤醒该线程
- 直接抛出
InterruptedException - 自动清除线程的中断标志位(这意味着如果在
catch块中不手动重新设置标志,后续无法再感知到这次中断)
wait()与sleep()的一致性
wait()和sleep()对中断的处理逻辑完全一致:只要线程处于这两种阻塞状态,调用interrupt()都会触发InterruptedException并清空中断标志。
代码示例
sleep()的中断处理
Thread sleepThread = new Thread(() -> { try { Thread.sleep(10000); // 线程进入10秒睡眠 } catch (InterruptedException e) { // 捕获中断异常,此时中断标志已被清除 System.out.println("睡眠线程被中断,当前中断标志:" + Thread.currentThread().isInterrupted()); // 若需传递中断,手动重新设置标志 Thread.currentThread().interrupt(); } }); sleepThread.start(); sleepThread.interrupt(); // 触发中断
wait()的中断处理
Object lockObj = new Object(); Thread waitThread = new Thread(() -> { synchronized (lockObj) { try { lockObj.wait(); // 线程进入等待状态 } catch (InterruptedException e) { System.out.println("等待线程被中断,当前中断标志:" + Thread.currentThread().isInterrupted()); Thread.currentThread().interrupt(); } } }); waitThread.start(); waitThread.interrupt(); // 触发中断
内容的提问来源于stack exchange,提问作者Ebenezer Rahul
相关产品推荐
相关产品推荐

