线程池(ThreadPoolExecutor)的execute方法如下,该方法在执行了读取语句:
int c = ctl.get()
后,执行了比较:
if (workerCountOf(c) < corePoolSize)
这两句之间没有添加任何保护线程安全的方法,所以execute是如何实现线程安全的呢?
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
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);
}
else if (!addWorker(command, false))
reject(command);
}
工作线程数小于核心线程数时,直接新建核心线程执行任务;
大于核心线程数时,将任务添加进等待队列;
队列满时,创建非核心线程执行任务;
工作线程数大于最大线程数时,拒绝任务
云安全开发者的大本营