Java优雅的停止线程

程序代码:
class TPTInterrupt { private Thread thread; public void start() { thread = new Thread(() -> { while (true) { Thread current = Thread.currentThread(); if (current.isInterrupted()) { System.out.println("料理后事"); break; } try { Thread.sleep(2000); System.out.println("将结果保存"); } catch (InterruptedException e) { current.interrupt(); } } }, "监控线程"); thread.start(); } public void stop() { thread.interrupt(); } } public static void main(String[] args) throws InterruptedException { TPTInterrupt t = new TPTInterrupt(); t.start(); Thread.sleep(3500); System.out.println("stop"); t.stop(); }

浙公网安备 33010602011771号