JDK1.5推出线程池,线程池底层构造方法
ThreadPoolExecutor(int corePoolSize, 核心线程数
int maximumPoolSize, 最大线程数
long keepAliveTime,存活时间
TimeUnit unit,存活单位
BlockingQueue<Runnable> workQueue 等待队列
RejectedExecutionHandler handler 拒绝策略
) {
newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>()(同步队列));
}
不推荐使用原因:有多少任务,就会创建多少非核心线程执行任务,会造成CPU100%
remark1:如果线程执行的速度大于线程提交的速度,会出现线程复用
newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()(无界队列));
}
不推荐使用原因:有多少任务,就会创建多少无界队列节点,可能会造成OOM
newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
不推荐使用原因:有多少任务,就会创建多少无界队列节点,可能会造成OOM
以上均不推荐使用,推荐自定义线程池
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10, 20, 0, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>());