多线程-安全的终止线程

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

posted @ 2019-08-29 23:44  莫己若  阅读(258)  评论(0编辑  收藏  举报