结论:
因核心线程数是0,任务提交后会进入到阻塞队列中,由于加入阻塞队列后会判断当前线程数是否为0,为0的话,会创建1个线程来执行阻塞队列中的任务,但该流程只会进入一次,则在整个流程中只会有一个线程来执行任务。
分析:
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);
// 若当前工作线程为0,会创建1个线程去执行阻塞队列中的人物
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
示例验证:
corePoolSize:0
maximumPoolSize:2
workQueue:LinkedBlockingQueue
提交10个任务
public void createThreadPool() {
ThreadPoolExecutor pool = new ThreadPoolExecutor(
0, 2, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
for (int i = 0; i < 10; i++) {
int j = i;
pool.execute(new Runnable() {
@Override
public void run() {
//获取线程名称
Thread thread = Thread.currentThread();
String name = thread.getName();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
//输出
int activeCount = pool.getActiveCount();
System.out.println("任务:"+j+"-----,线程名称:"+name+"-----活跃线程数:"+activeCount);
}
});
}
pool.shutdown();
}
结果: