ThreadPoolExecutor的shutDown和shutDownNow的區別

import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2017/3/23.
 *
 * ExecutorService  的 shutDown 和 shutDownNow  ,
 * shutDown 不在接受新的線程,並且等待之前提交的線程都執行完在關閉,
 * shutDownNow 直接關閉活躍狀態的所有的線程 , 並返回等待中的線程
 *
 * 該測試 由於 MyThread sleep時間是隨機的, 所以會出現不同的情況
 *
 * 1. 有一個線程 sleep時間小於2000 則會直接運行完, 然後等待中的線程開始活躍, 這時候shutDownNow 可能全都運行完或者 部分被catch 輸出shutDown
 * 2. 所有線程都是>2000 時間, 導致shutDownNow 的時候 還有線程在等待, 從而最後得到的list 是等待中的線程
 */
public class ExecutorServiceShutDownTest {

    public static void main(String[] args) throws InterruptedException {

        class MyThread implements Runnable{

            public void run() {
                try {
                    Random random = new Random();
                    int time = 1000 * (random.nextInt(5)+1);
                    Thread.sleep(time);
                    System.out.println(Thread.currentThread().getName() + " complete , time = "+time);
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + " Interrupted!");
                }
            }
        }

        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.submit(new MyThread());
        executorService.submit(new MyThread());
        executorService.submit(new MyThread());
        executorService.submit(new MyThread());

        Thread.sleep(2000);

//        executorService.shutdown();
        List<Runnable> list = executorService.shutdownNow();
        System.out.println(list.size());




    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章