首页 > 编程语言 > 详细

如何优雅地结束线程的生命周期

时间:2019-12-17 12:21:18      阅读:87      评论:0      收藏:0      [点我收藏+]

使用开关的方式停止线程

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

 

如何优雅地结束线程的生命周期

原文:https://www.cnblogs.com/zheaven/p/12053449.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!