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,停止多余的线程并保留核心数量的线程是没有规律或规则

  • 相关阅读:
    Android复习(五)设备兼容—>多apk支持
    Android复习(五)设备兼容—>支持刘海屏
    KVC给只读属性进行赋值..
    pods 终端安装 第三方框架的一些命令
    使用SnakeKit怎么设置动画效果 以及 UIView的弹簧动画效果
    Cocoa、Foundation、UIKit、Objective-c、XCode、Interface Builder的概念
    仿写SDWebImage中的一个网络加载图片的框架
    TCP/IP 短链接 长链接 scoket
    init 和 initWithFrame 区别
    JSON XML 数据解析
  • 原文地址:https://www.cnblogs.com/acode/p/8657704.html
Copyright © 2011-2022 走看看