Java并发05:线程的中断机制 - 优雅地停止线程

引言:停止线程的困境 假设你正在开发一个下载工具,用户点击"取消"按钮,应该如何停止下载线程? // 某个下载任务正在执行 Thread downloadThread = new Thread(() -> { while (true) { downloadData(); // 持续下载 } }); downloadThread.start(); // 用户点击"取消"按钮 // ❌ 如何停止这个线程? downloadThread.stop(); // 已废弃,不能用! 为什么Thread.stop()被废弃?如何正确停止线程? 一、为什么不能用stop()? 1.1 stop()的问题 public class StopProblemDemo { private int balance = 1000; // 银行账户余额 public synchronized void transfer(int amount) { balance -= amount; // 步骤1:扣款 // 如果在这里被stop()... balance += amount; // 步骤2:到账 } public static void main(String[] args) throws Exception { StopProblemDemo account = new StopProblemDemo(); Thread thread = new Thread(() -> { account.transfer(500); }); thread.start(); Thread.sleep(1); // 让线程执行一半 thread.stop(); // ← 强制停止 System.out.println("余额: " + account.balance); // 500?1000? } } 问题: ...

2025-11-20 · maneng

如约数科科技工作室

浙ICP备2025203501号

👀 本站总访问量 ...| 👤 访客数 ...| 📅 今日访问 ...