java如何中断
中断线程的方法
在Java中,中断线程主要通过Thread.interrupt()方法实现。该方法会设置线程的中断标志位,但并不会强制终止线程的执行。线程需要检查中断状态并自行决定如何响应中断。
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// 执行任务
}
});
thread.start();
// 中断线程
thread.interrupt();
检查中断状态
线程可以通过Thread.currentThread().isInterrupted()或静态方法Thread.interrupted()检查中断状态。后者会清除中断标志位。

if (Thread.interrupted()) {
// 处理中断逻辑
throw new InterruptedException();
}
处理阻塞操作的中断
当线程在阻塞操作(如Object.wait()、Thread.sleep())中被中断时,会抛出InterruptedException。捕获该异常后应恢复中断状态。

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// 恢复中断状态
Thread.currentThread().interrupt();
}
使用Future取消任务
通过ExecutorService提交的任务可以使用Future.cancel(true)来中断线程。
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> future = executor.submit(() -> {
// 任务代码
});
// 取消任务
future.cancel(true);
自定义中断策略
对于不响应中断的代码,可以自定义中断策略,例如通过标志变量控制线程退出。
class CustomTask implements Runnable {
private volatile boolean stopped = false;
public void stop() { stopped = true; }
@Override
public void run() {
while (!stopped) {
// 执行任务
}
}
}
注意事项
中断机制是协作式的,线程必须主动检查中断状态才能响应中断。直接调用Thread.stop()已废弃,因其可能导致对象状态不一致。处理中断时应确保资源正确释放,避免线程泄露。






