我们单纯的去创建一个线程可以用new Thread
但是这个有弊端,就是再高并发的情况,new Thread 每次都要去创建一个线程,用完需要摧毁它,这样非常的消耗时间。线程多的情况下没办法统一管理。
如何统一管理线程和复用已经创建的线程呢?
就有了线程池这个概念。线程池的工作流程:
Java 常规的线程池有四种:newCachedThreadPool,newFixedThreadPool,newScheduledThreadPool,newSingleThreadExecutor,这四种都是Executors提供的。都是通过ThreadPoolExecutor实现的。先介绍下ThreadPoolExecutor。
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters and default thread factory and rejected execution handler.
* It may be more convenient to use one of the {@link Executors} factory
* methods instead of this general purpose constructor.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSi