如何优雅地结束线程的生命周期 使用开关的方式停止线程 通过打断sleep()来停止线程 通过修改线程的状态来停止线程

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();
    }
}

通过打断sleep()来停止线程

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(); } }