1.核心线程是否会被回收?
不会被回收,除非手动设置allowCoreThreadTimeOut参数
2.keepAliveTime的含义
这个参数的含义是指当线程池中线程数量大于corePollSize时,此时存在非核心线程,keepAliveTime指非核心线程空闲时间达到的阈值会被回收。
3.常见的三个线程池
ExecutorService service = Executors.newFixedThreadPool(20);
ExecutorService service2 = Executors.newCachedThreadPool();
ExecutorService service3 = Executors.newSingleThreadExecutor();
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>()));
}
它两唯一的区别是传入参数作为核心线程大小和固定为1
3)缓冲线程池
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
它用到了同步队列,没有内存开销问题
4.工作中的线程池
队列一般设置成ArrayBlockQueue,大小设置成500,核心的线程数根据机器的核数*2+1来设置,这样是为了更好利用资源,又不让系统OOM
源码解读:
https://www.cnblogs.com/semi-sub/p/13908099.html
原文:https://www.cnblogs.com/johnzhao/p/14635456.html