Java线程池停止空闲线程是否有规则呢?

Java线程池中线程的数量超过核心线程的数量,且所有线程空闲,空闲时间超过keepAliveTime,会停止超过核心线程数量的线程,那么会保留哪些线程呢?是不是有规则呢?

测试代码:

       ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 5, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5));
        int taskNum = 13;
        for (int i = 0; i < taskNum; i++) {
            final int finalI = i;
            if (i == 10) {
                System.out.println("执行过10个任务,开始空闲");
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("提交任务:" + (i + 1));
            executor.submit(new Runnable() {
                public void run() {
                    Integer taskNum = finalI + 1;
                    System.out.println("task: " + taskNum + ", " + Thread.currentThread().getName() + ", " + System.currentTimeMillis());
                }
            });
        }

运行结果

提交任务:1
提交任务:2
提交任务:3
提交任务:4
提交任务:5
提交任务:6
提交任务:7
提交任务:8
提交任务:9
提交任务:10
执行过10个任务,开始空闲
task: 2, pool-1-thread-2, 1522134893596
task: 1, pool-1-thread-1, 1522134893596
task: 3, pool-1-thread-3, 1522134893596
task: 9, pool-1-thread-4, 1522134893596
task: 4, pool-1-thread-2, 1522134893596
task: 6, pool-1-thread-4, 1522134893596
task: 5, pool-1-thread-3, 1522134893596
task: 8, pool-1-thread-1, 1522134893596
task: 7, pool-1-thread-2, 1522134893596
task: 10, pool-1-thread-5, 1522134893596
提交任务:11
提交任务:12
提交任务:13
task: 11, pool-1-thread-6, 1522134903606
task: 13, pool-1-thread-8, 1522134903606
task: 12, pool-1-thread-7, 1522134903606

根据多次试验,发现每次保留作为核心线程的线程并没规律或规则。因此,线程池中线程数量达到最大允许的线程数量,然后所有线程都同时进入空闲状态且空闲时间超过keepAliveTime,停止多余的线程并保留核心数量的线程是没有规律或规则

posted @ 2018-03-27 15:27  Acode  阅读(2683)  评论(0编辑  收藏  举报
您是本站第访问量位访问者!