image.png
上面是提交了任务后,线程池处理流程。如果想在任务提交前预热线程池可以使用prestartAllCoreThreads提前创建线程。
需要注意的是,上图中两个地方的创建线程都是需要加锁的,相关代码如下图:

private boolean addWorker(Runnable firstTask, boolean core) {
        retry:
        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // Check if queue empty only if necessary.
            if (rs >= SHUTDOWN &&
                ! (rs == SHUTDOWN &&
                   firstTask == null &&
                   ! workQueue.isEmpty()))
                return false;

            for (;;) {
                int wc = workerCountOf(c);
                if (wc >= CAPACITY ||
                    wc >= (core ? corePoolSize : maximumPoolSize))
                    return false;
                if (compareAndIncrementWorkerCount(c))
                    break retry;
                c = ctl.get();  // Re-read ctl
                if (runStateOf(c) != rs)
                    continue retry;
                // else CAS failed due to workerCount change; retry inner loop
            }
        }

        boolean workerStarted = false;
        boolean workerAdded = false;
        Worker w = null;
        try {
            //这里的内部类Worker继承了AbstractQueuedSynchronizer,也实现了Runnable
            //Worker里面有个Thread属性,每次创建任务的时候都会对应创建一个线程
            w = new Worker(firstTask);
            final Thread t = w.thread;
            if (t != null) {
                final ReentrantLock mainLock = this.mainLock;
                //加锁
                mainLock.lock();
                try {
                    // Recheck while holding lock.
                    // Back out on ThreadFactory failure or if
                    // shut down before lock acquired.
                    int rs = runStateOf(ctl.get());

                    if (rs < SHUTDOWN ||
                        (rs == SHUTDOWN && firstTask == null)) {
                        if (t.isAlive()) // precheck that t is startable
                            throw new IllegalThreadStateException();
                        workers.add(w);
                        int s = workers.size();
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                if (workerAdded) {
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }

这里再列一下几种任务队列:

  • ArrayBlockingQueue:基于数组结构的有界阻塞队列,队列按FIFO原则对元素进行排序。
  • LinkedBlockingQueue:基于链表结构的阻塞队列,同样按FIFO原则排序,吞吐量通常高于ArrayBlockingQueue。
  • SynchronousQueue:本身不存储元素的阻塞队列,每次插入须等到另一个线程调用移除操作,否则插入操作会一直阻塞,吞吐量要高于LinkedBlockingQueue。
  • PriorityBlockingQueue:具有优先级的无限阻塞队列。

几种饱和策略:

  • AbortPolicy:直接抛出异常(默认)
  • CallerRunsPolicy:使用调用者所在线程运行
  • DiscardPolicy:丢弃队列里最近的一个任务,并执行当前任务
  • dISCARDPolicy:不处理,丢弃掉

当然也可以实现RejectedExecutionHandler接口自定义策略进行处理。


步履不停
38 声望13 粉丝

好走的都是下坡路