zoukankan      html  css  js  c++  java
  • 如何优雅地结束线程的生命周期

    使用开关的方式停止线程

    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(); } }
  • 相关阅读:
    UVA-11437 Triangle Fun
    UVA 10491
    CF 223C
    poj 3273
    由异常掉电问题---谈xfs文件系统
    好久没有写博客了,最近一段时间做一下总结吧!
    Json.Net
    div 旋转
    VirtualBox虚拟机网络设置
    windows 2003 安装 MVC 环境 404错误,无法找到该页
  • 原文地址:https://www.cnblogs.com/zheaven/p/12053449.html
Copyright © 2011-2022 走看看