一.线程池用法
1.Executors类用于创建线程池对象,线程池对象用ExecutorService接口接受
2.这是API中Executors创建线程池的3大常用方法
1.public static ExecutorService newFixedThreadPool(int nThreads)//一个线程池nThreads个工作线程,类似于一个银行nThreads个工作窗口
2.public static ExecutorService newSingleThreadExecutor()//一个线程池1个工作线程,类似于一个银行1个工作窗口
3.public static ExecutorService newCachedThreadPool()//一个线程池动态创建线程,当池子中的线程个数不足以处理任务时,就会创建新的线程来处理任务
总结:方法1和2都有弊端,故方法3最为合适
1.方法1的弊端是如果线程任务很少,但是线程持中的线程很多,那么就会造成线程资源的浪费
2.方法2的弊端是,只有一个线程,但是任务很多,这时候任务执行就非常满,效率很低(直接变成了串行,而非并发)
二.线程池源码剖析
1.public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
2.public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
3.public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
一.观察上述源码可以发现
1.newFixedThreadPool(int nThreads)
2.newSingleThreadExecutor()
3.newCachedThreadPool(),
这三大常用创建线程池的方法实际上都是new ThreadPoolExecutor()对象,只是参数有所不同
二.ThreadPoolExecutor构造方法中各参数的意义
public ThreadPoolExecutor(int corePoolSize,//核心线程数
int maximumPoolSize,//最大线程数
long keepAliveTime,//扩容线程存活时间
TimeUnit unit,//时间单位
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
1.int corePoolSize,//核心线程数
2.int maximumPoolSize,//最大线程数
3.long keepAliveTime,//扩容线程存活时间,当线程池中线程数大于核心线程数时,如果某些线程超过了keepAliveTime时间没有被使用,那么就会被销毁
4.TimeUnit unit,//时间单位
5.BlockingQueue< Runnable >workQueue//阻塞队列