调用Thread.interrupt()设置中断标志,阻塞时抛出InterruptedException并清除标志,线程需检查中断状态或捕获异常以响应中断。示例中worker线程循环检测中断,sleep时被中断后重新设置中断状态并退出。关键点包括不忽略InterruptedException、重置中断状态、主动轮询isInterrupted()。注意interrupt不能强制终止运行中的线程,必须由线程协作实现取消。

在Java中,Thread.interrupt() 是一种协作式中断机制,用于请求线程停止当前工作。它不会强制终止线程,而是通过设置线程的中断状态来通知线程“应该中断”,由线程自身决定如何响应。
调用 thread.interrupt() 会将目标线程的中断标志位设为 true。如果该线程正在阻塞(如 sleep、wait、join 等),则会抛出 InterruptedException,同时清除中断状态。线程需要定期检查中断状态并做出适当处理。
以下是一个使用 interrupt 安全取消线程的示例:
public class InterruptExample {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
System.out.println("工作线程运行中...");
Thread.sleep(1000); // 模拟耗时操作
} catch (InterruptedException e) {
System.out.println("线程被中断,准备退出");
Thread.currentThread().interrupt(); // 重新设置中断状态
break;
}
}
System.out.println("线程已安全退出");
});
worker.start();
Thread.sleep(3000);
worker.interrupt(); // 发起中断请求
}
}
不能通过 interrupt 强制结束一个正在执行普通代码的线程。若线程未处于阻塞状态且未主动检查中断状态,则中断不会生效。因此,良好的线程设计必须包含对中断的响应逻辑。
立即学习“Java免费学习笔记(深入)”;
基本上就这些。只要线程配合中断机制,就能实现安全、优雅的线程取消。
以上就是在Java中如何使用Thread.interrupt取消线程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号