package com.dwz.concurrency.chapter6; /** * 使用开关的方式停止线程 */ public class ThreadCloseGraceful { private static class Worker extends Thread { private volatile boolean start = true; @Override public void run() { System.out.println("running..."); while(start) { } System.out.println("finish done..."); } public void shutdown() { this.start = false; } } public static void main(String[] args) { Worker worker = new Worker(); worker.start(); try { Thread.sleep(5_000); } catch (InterruptedException e) { e.printStackTrace(); } worker.shutdown(); } }
package com.dwz.concurrency.chapter6; public class ThreadCloseGraceful2 { private static class Worker extends Thread { @Override public void run() { System.out.println("running..."); while(true) { try { Thread.sleep(1_000); } catch (InterruptedException e) { e.printStackTrace(); break; } } System.out.println("finish done..."); } } public static void main(String[] args) { Worker worker = new Worker(); worker.start(); try { Thread.sleep(5_000); } catch (InterruptedException e) { e.printStackTrace(); } worker.interrupt(); } }
package com.dwz.concurrency.chapter6; public class ThreadCloseGraceful3 { private static class Worker extends Thread { @Override public void run() { System.out.println("running..."); while(true) {
//Thread.currentThread().isInterrupted()也可以 if(Thread.interrupted()) { break; } } System.out.println("finish done..."); } } public static void main(String[] args) { Worker worker = new Worker(); worker.start(); try { Thread.sleep(5_000); } catch (InterruptedException e) { e.printStackTrace(); } worker.interrupt(); } }
原文:https://www.cnblogs.com/zheaven/p/12053449.html