直接上代码 /** * 优雅的关闭线程. */ public class ShutDown { public static void main(String[] args) throws InterruptedException { Runner one = new Runner(); Thread countThread = new Thread(one, "countThread"); countThread.start(); TimeUnit.SECONDS.sleep(1); countThread.interrupt(); // 调用interrupt, 打断线程执行. Runner two = new Runner(); countThread = new Thread(two, "countThread"); countThread.start(); TimeUnit.SECONDS.sleep(1); two.cancel(); // 通过改变flag, 停止线程 } static class Runner implements Runnable { private long value; private volatile boolean on = true; @Override public void run() { /** * 因此, 通过监听interrupt或者flag, 就可以判断线程是否停止; * 然后做一些相关资源的释放. */ while (on && !Thread.currentThread().isInterrupted()) { value++; } System.out.println("value: " + value); } public void cancel() { this.on = false; } } }