线程池的处理流程

先抛个问题,如果一个线程池的核心线程是5,目前3个核心线程被创建,其中1个在运行,2个空闲,缓存队列为空。此时新进来一个任务,线程池会做什么操作?

空闲的核心线程会直接执行这个任务吗?

会先丢到队列里再说吗?

答案都是否定的。

我们看下下面的线程处理流程图

别人说的都不算,还得看源码,摘出了java.util.concurrent.ThreadPoolExecutor#execute的源码
 1 public void execute(Runnable command) {
 2         if (command == null)
 3             throw new NullPointerException();
 4         /*
 5          * Proceed in 3 steps:
 6          *
 7          * 1. If fewer than corePoolSize threads are running, try to
 8          * start a new thread with the given command as its first
 9          * task.  The call to addWorker atomically checks runState and
10          * workerCount, and so prevents false alarms that would add
11          * threads when it shouldn't, by returning false.
12          *
13          * 2. If a task can be successfully queued, then we still need
14          * to double-check whether we should have added a thread
15          * (because existing ones died since last checking) or that
16          * the pool shut down since entry into this method. So we
17          * recheck state and if necessary roll back the enqueuing if
18          * stopped, or start a new thread if there are none.
19          *
20          * 3. If we cannot queue task, then we try to add a new
21          * thread.  If it fails, we know we are shut down or saturated
22          * and so reject the task.
23          */
24         int c = ctl.get();
25 if (workerCountOf(c) < corePoolSize) { 26 if (addWorker(command, true)) 27 return; 28 c = ctl.get(); 29 } 30 if (isRunning(c) && workQueue.offer(command)) { 31 int recheck = ctl.get(); 32 if (! isRunning(recheck) && remove(command)) 33 reject(command); 34 else if (workerCountOf(recheck) == 0) 35 addWorker(null, false); 36 } 37 else if (!addWorker(command, false)) 38 reject(command); 39 }
上面的条件判断见名知义即可:
如果当前运行的线程数小于核心线程数,会先创建出一个线程来执行这个任务。
否则会先丢到队列中,如果队列满了
再添加线程,如果已经超过最大线程,则拒绝

原文地址:https://www.cnblogs.com/sulishihupan/p/14352543.html