zoukankan      html  css  js  c++  java
  • 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,停止多余的线程并保留核心数量的线程是没有规律或规则

  • 相关阅读:
    PHP加速器eAccelerator安装
    WCF
    WCF
    WCF
    前端学习书籍推荐
    问题集录01--java对list列表进行排序
    基础知识:字符编码
    基础知识:if条件、while循环、for循环 相关练习
    基础知识:语言、编程、计算机组成、cpu、存储器
    视图 索引 存储过程
  • 原文地址:https://www.cnblogs.com/acode/p/8657704.html
Copyright © 2011-2022 走看看