美文网首页
ThreadPoolExecutor使用LinkedBlocki

ThreadPoolExecutor使用LinkedBlocki

作者: 童话里的小超人 | 来源:发表于2018-08-24 00:02 被阅读0次

坑的描述

ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
    4, // corePoolSize
    64, // maximumPoolSize
    60L, // keepAliveTime
    TimeUnit.SECONDS, // timeUnit
    new LinkedBlockingQueue<>(100000) // workQueue
);

我们有时候会使用上述的代码来新建一个ThreadPoolExecutor对象,使用LinkedBlockingQueue作为workQueue。

需要特别注意的是,上述创建的ThreadPoolExecutor对象,当同时有64个任务进来时,并不会创建64个线程来同时处理这64个任务,而只创建4个core线程优先处理最先进来的4个任务,将后进来的60个任务放入LinkedBlockingQueue队列中,队列中的任务排队等待被这4个core线程处理。

使用LinkedBlockingQueue作为workQueue,ThreadPoolExecutor对象在队列不满的情况下只会创建core线程,不会创建非core线程,设置的maximumPoolSize并不起作用。

原因分析

下述代码是ThreadPoolExecutor的execute方法,其中描述了新建线程的机制。可以发现只有当满足下面的两个条件之一时,才会新建线程:

  1. 当前存活的线程数小于corePoolSize;(新建core线程)
  2. 往workQueue添加元素失败;(新建非core线程)
    public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) { // 条件1:存活线程小于corePoolSize,新建core线程
            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);
        }
        else if (!addWorker(command, false)) // 条件2:往队列添加元素失败,新建非core线程
            reject(command);
    }

可以发现能新建非core线程的直接原因是队列workQueue添加元素失败,因此选择不同的BlockingQueue实现类会对新建线程产生很大的影响,常用的BlockingQueue:

  • LinkedBlockingQueue:队列已满时会添加失败;
  • SynchronousQueue:如果没有其他线程在等待获取元素时会添加失败;

可以参考Executors创建ThreadPoolExecutor的几种方法。

相关文章

网友评论

      本文标题:ThreadPoolExecutor使用LinkedBlocki

      本文链接:https://www.haomeiwen.com/subject/ttpviftx.html