ThreadPoolExecutor的shutDown和shutDownNow的区别

来源:互联网 发布:计划软件手机版 编辑:程序博客网 时间:2024/05/20 18:44
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());    }}

0 0
原创粉丝点击