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());




    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值