ThreadPool技术分析
ThreadPool是我们进行并发开发中肯定要使用的一个强大工具,因为创建线程不仅要在VM栈分配新的线程执行栈,而且要调native方法对线程做创建和初始化,是个相当占用资源的事情。如果宿主机操作系统使用的KLT的话,不断的创建和销毁线程对程序的性能影响更加严重。
本文将以java.util.concurrent.ThreadPoolExecutor
为例,简单地分析一下ThreadPool的实现原理。
首先,我们先看看java.util.concurrent.ThreadPoolExecutor#execute
/**
* Executes the given task sometime in the future. The task
* may execute in a new thread or in an existing pooled thread.
*
* If the task cannot be submitted for execution, either because this
* executor has been shutdown or because its capacity has been reached,
* the task is handled by the current {@code RejectedExecutionHandler}.
*
* @param command the task to execute
* @throws RejectedExecutionException at discretion of
* {@code RejectedExecutionHandler}, if the task
* cannot be accepted for execution
* @throws NullPointerException if {@code command} is null
*/
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* t