zoukankan      html  css  js  c++  java
  • 多线程-安全的终止线程

    package com.bee.thread;
    
    import java.util.concurrent.TimeUnit;
    
    /**
     * @date 2019-08-29 23:32
     * <p>
     * 在实例的执行过程中,main线程通过终端操作和cancel() 方法均可以使CountThread 得以终止,
     * 这种通过标识位或者中断操作的方式能够使线程在中止的时候有机会去清理资源,而不是武断的将线程停止。
     * 因此这种终止线程的做法显得更加安全和优雅
     */
    public class ShutDown {
    
        public static void main(String[] args) {
    
    
            Runner runner1 = new Runner();
            Thread currentThread = new Thread(runner1, "countThread");
            currentThread.start();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            currentThread.interrupt();
            Runner runner2 = new Runner();
            currentThread = new Thread(runner2, "countThread");
            currentThread.start();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runner2.cancel();
    
        }
    
        private static class Runner implements Runnable {
    
            private long i;
    
            private volatile boolean on = true;
    
            @Override
            public void run() {
                while (on && !Thread.currentThread().isInterrupted()) {
                    i++;
                }
                System.out.println("count = " + i);
            }
    
            private void cancel() {
                this.on = false;
            }
        }
    }
    
    
    人的潜力是可以激发的,比如说你给我50斤的砖我可能拎不动,但你要是给我100斤的人民币我肯定拎起来就跑。
  • 相关阅读:
    python-day24(模块语法)
    python-day23(正则表达式,RE)
    python-day22(序列化)
    python-day21(模块初级)
    python-day20(继承)
    python-day19(约束和异常处理)
    python-day18(反射)
    延迟任务
    亚马逊服务器创建root用户
    sqlalchemy orm
  • 原文地址:https://www.cnblogs.com/mojiruo/p/11432694.html
Copyright © 2011-2022 走看看