为了更好的控制多线程,JDK提供了一套线程框架Executors.存在于java.util.concurrent包中。是JDK并发的核心包。
标题 ##1.Executors创建线程池的方法
1).newFixedThreadPool(),返回一个固定数量的线程池。该方法的线程数量始终不变,当有一个任务提交时,若线程池中有线程空闲,则立即执行。如没有,则会被暂缓在一个任务队列中等待空闲的线程执行。
2).newSingleThreadExecutor(),创建一个线程的线程池,如空闲则执行,如没有,则会被暂缓在一个任务队列中。
3).newCachedThreadPool(),返回一个可以根据时间情况调整线程数量的线程池,不限制最大线程数量。如有空闲的线程则执行任务,没有任务则不创建线程。并且每一个空闲线程会在60秒后自动回收。
4).newScheduledThreadPool(),返回一个SchededExecutorServiced对象,该线程池可以指定线程的数量。
以上几种创建线程池的方法会获得不同功能的线程池。观察JDK源码就会发现,其实都是通过ThreadPoolExecutor这个类是实现的。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
/*
ThreadPoolExecutor
1.corePoolSize 核心线程数,即初始化线程池时存在的线程数
2.maximumPoolSize 最大线程数
3.keepAliveTime 线程空闲(存活)时间
4.unit 时间单位
5.workQueue 存放线程的缓存队列
6.handler 拒绝执行的方法
*/
new ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
)