关于ThreadPoolExecutor的corePoolSize和maximuxPoolSize大小的说明

1.结论

看了一些博客,里面关于corePoolSize和maximuxPoolSize大小说得都不大一样,就做了个简单实验。先说结论吧。

1.当加入的工作线程数小于corePoolSize,会新创建线程.
2.之后添加的线程会加入到阻塞队列,比如Executors.newFixedThreadPool创建的阻塞队列是LinkedBlockingQueue。
3.当阻塞队列满了的时候,会接着创建线程,直到活跃线程数达到maximuxPoolSize.
4.如果线程池里面的工作线程还没有释放,再接着添加线程的话,就会触发RejectedExecutionHandler.

用默认的Executors.newFixedThreadPool,创建的阻塞队列是无界队列(队列大小是Integer.MAX_VALUE),一直存储在内存中,就永远也不会触发到RejectedExecutionHandler了。 所以推荐创建线程池的方法是使用ThreadPoolExecutor,而不是Executors.

2.实验

实验如下:

public static void main(String[] args) {

    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 0, TimeUnit.MINUTES,
            new LinkedBlockingQueue<>(10), new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            System.out.print("rejected");
        }
    });
    for(int i=0; i< 30; i++) {
        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    //让线程一直运行
                }
            }
        });
        System.out.println(i + ": " + threadPoolExecutor.getActiveCount());
    }
}

输出是:

0: 1
1: 2
2: 3
3: 4
4: 5
5: 5
6: 5
7: 5
8: 5
9: 5
10: 5
11: 5
12: 5
13: 5
14: 5
15: 6
16: 7
17: 8
18: 9
19: 10
rejected20: 10
rejected21: 10
rejected22: 10
rejected23: 10
rejected24: 10
rejected25: 10
rejected26: 10
rejected27: 10
rejected28: 10
rejected29: 10

3.源码

ThreadPoolExecutor.execute

public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    /*
     * Proceed in 3 steps:
     *
     * 1. If fewer than corePoolSize threads are running, try to
     * start a new thread with the given command as its first
     * task.  The call to addWorker atomically checks runState and
     * workerCount, and so prevents false alarms that would add
     * threads when it shouldn't, by returning false.
     *
     * 2. If a task can be successfully queued, then we still need
     * to double-check whether we should have added a thread
     * (because existing ones died since last checking) or that
     * the pool shut down since entry into this method. So we
     * recheck state and if necessary roll back the enqueuing if
     * stopped, or start a new thread if there are none.
     *
     * 3. If we cannot queue task, then we try to add a new
     * thread.  If it fails, we know we are shut down or saturated
     * and so reject the task.
     */
    int c = ctl.get();
    //活跃线程数小于corePoolSize
    if (workerCountOf(c) < corePoolSize) {
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }
    //阻塞队列还能放入线程
    if (isRunning(c) && workQueue.offer(command)) {
        int recheck = ctl.get();
        if (! isRunning(recheck) && remove(command))
            reject(command);
        //没有现成运行了
        else if (workerCountOf(recheck) == 0)
            addWorker(null, false);
    }
    //阻塞队列不能放入线程了,尝试增加工作线程数直到maximumPoolSize
    else if (!addWorker(command, false))
        reject(command);
}

至于addWorker方法,就不贴出来了,网上专门分析线程池的帖子很多,这里主要只讲corePoolSize和maximuxPoolSize。作用是addWorker的第二个参数core=true的时候,只会增加线程到corePoolSize; 是false的时候增加线程到maximumPoolSize。 这也论证了刚刚的结论和实验。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值