用支持中断感知的任务取消,取代 Thread.stop() 和临时共享标志。
代码对比
✕ Forced thread termination
Thread worker = new Thread(this::runTask); worker.start(); // May stop the thread while shared state is inconsistent. worker.stop();
✓ Future cancellation
Future<?> worker = executor.submit(this::runTask); // Requests interruption; the task must cooperate. worker.cancel(true);
发现此代码有问题? 告诉我们。
为什么现代方式更好
保持不变量
任务只在为取消而设计的代码路径上停止。
统一控制
Future 将执行、完成和取消统一表示。
可组合
中断机制与阻塞队列、锁、执行器和虚拟线程协同工作。
旧方式
Thread.stop()
现代方式
Future.cancel(true)
自 JDK
5
难度
高级
JDK 支持
从不安全的线程终止到协作式取消
可用
Future 和 ExecutorService 自 JDK 5(2004 年 9 月)起可用。
工作原理
Thread.stop() 可能在代码持有监视器或正在更新共享状态时终止线程,导致对象损坏。现代取消方式是协作式的:使用中断取消 Future,尽可能传播 InterruptedException,无法传播时恢复中断状态,并将任务设计为能够到达安全的取消点。
相关文档
证明