java 中中断线程阻塞的核心做法是调用 thread.interrupt(),它会设置线程的中断标志位。如果目标线程处于可中断的阻塞状态(如等待锁、sleep 或 wait),jvm 会自动抛出 interruptedexception 并清除中断标志;若线程未阻塞,则仅保留标志位供后续轮询检查。

sleep() 被中断时的异常处理流程
当线程执行 Thread.sleep() 时,若其他线程对其调用 interrupt(),该线程会立即从睡眠中唤醒并抛出 InterruptedException。此时线程不再继续休眠,而是进入异常处理逻辑,通常用于清理资源或退出循环。

public class SleepInterruptDemo {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
try {
System.out.println("Start sleeping...");
Thread.sleep(5000);
System.out.println("Finished sleeping.");
} catch (InterruptedException e) {
System.out.println("Sleep interrupted! Flag: " + Thread.currentThread().isInterrupted());
}
});
t.start();
Thread.sleep(1000); // Wait a bit
t.interrupt(); // Interrupt the sleeping thread
t.join(); // Wait for thread to finish
}
}
预期结果:控制台先打印 “Start sleeping...”,约 1 秒后打印 “Sleep interrupted! Flag: false”。注意 catch 块中 isInterrupted() 返回 false,因为抛出异常时 JVM 已自动清除了中断标志。
wait() 在同步块中被中断的行为
在线程持有对象锁并调用 Object.wait() 时,若被外部中断,同样会抛出 InterruptedException 并释放锁。与 sleep 不同,wait 的中断通常发生在条件不满足时的等待阶段,开发者需在 catch 块中重新检查条件或决定是否退出。

import java.util.concurrent.locks.ReentrantLock;
public class WaitInterruptDemo {
private final ReentrantLock lock = new ReentrantLock();
private boolean ready = false;
public void waitForReady() throws InterruptedException {
lock.lock();
try {
while (!ready) {
System.out.println("Waiting for ready...");
lock.wait(); // Note: wait() must be called inside synchronized block or using Object monitor
// For ReentrantLock, we should use Condition.await(), but here we simulate with Object.wait via synchronized block
}
System.out.println("Ready!");
} catch (InterruptedException e) {
System.out.println("Wait interrupted. Ready status: " + ready);
throw e; // Or handle appropriately
} finally {
lock.unlock();
}
}
public void setReady() {
lock.lock();
try {
ready = true;
lock.notifyAll();
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
WaitInterruptDemo demo = new WaitInterruptDemo();
Thread waiter = new Thread(() -> {
try {
demo.waitForReady();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
waiter.start();
Thread.sleep(1000);
waiter.interrupt();
waiter.join();
}
}
预期结果:控制台打印 “Waiting for ready...”,随后打印 “Wait interrupted. Ready status: false” 及堆栈跟踪。由于 wait() 必须在同步块内调用,上述代码需调整为使用 synchronized 关键字包裹 wait() 调用,或使用 ReentrantLock 对应的 Condition 对象。为简化演示,实际生产中推荐使用 Condition.await(),其在中断时也会抛出 InterruptedException 并恢复中断状态。
中断标志对非阻塞线程的影响
若线程未处于阻塞状态,interrupt() 不会强制终止它,仅设置中断标志位。开发者需主动通过 Thread.isInterrupted() 或 Thread.interrupted() 检查标志,并在检测到中断后自行决定退出逻辑。这是实现优雅关闭的关键模式。
public class PollingInterruptDemo {
public static void main(String[] args) {
Thread worker = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Working...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore interrupt status
break;
}
}
System.out.println("Worker exiting due to interrupt.");
});
worker.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
worker.interrupt();
try {
worker.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
预期结果:控制台每 1 秒打印一次 “Working...”,共三次,随后打印 “Worker exiting due to interrupt.”。注意在 catch 块中重新设置中断标志,以确保外层能感知到中断意图。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











