← 中文资源

简体中文版本

Thread 中断的协作式取消

中断是协作式的:任务循环自查 isInterrupted、阻塞的 sleep 抛 InterruptedException;捕获后恢复中断标志再退出,shutdownNow 只负责发送信号。

阅读英文原文

实现说明

Thread 中断的协作式取消的核心是类 CancellableWorker。 这个示例中仅有的重复出现在 while (!Thread.currentThread().isInterrupted()) 里。

使用要点

  • 每一步打印都带着自己的标签:worker stopped: interrupted=。

常见问题

运行「Thread 中断的协作式取消」会打印什么?

运行文件本身,worker stopped: interrupted= 这些前缀各对应一段演示逻辑。

核心语句

ExecutorService executor = Executors.newSingleThreadExecutor();
while (!Thread.currentThread().isInterrupted()) {
    try {
        TimeUnit.MILLISECONDS.sleep(10); // 可中断的阻塞点
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt(); // 恢复标志再退出
        break;
    }
}

代码示例

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class CancellableWorker {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        // 中断是协作式的:任务自己查 isInterrupted 标志决定何时退出
        executor.submit(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    TimeUnit.MILLISECONDS.sleep(10); // 可中断的阻塞点
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); // 恢复标志再退出
                    break;
                }
            }
            System.out.println("worker stopped: interrupted="
                    + Thread.currentThread().isInterrupted());
        });

        TimeUnit.MILLISECONDS.sleep(50);
        executor.shutdownNow(); // 向所有任务发送中断信号
        executor.awaitTermination(1, TimeUnit.SECONDS);
    }
}