Java常用的线程池有FixedThreadPool和CachedThreadPool,我们可以通过查看他们的源码来进行学习。
Java的源码下载参考这篇文章:Java源码下载和阅读(JDK1.8) - zhangpeterx的博客
在源码的目录java/util/concurrent下找到Executors.java文件查看源码。
里面提到的封装类有:
newScheduledThreadPool,newSingleThreadScheduledExecutor,newCachedThreadPool,newSingleThreadExecutor,newFixedThreadPool,newWorkStealingPool,newFixedThreadPool
我这里只把newFixedThreadPool,newCachedThreadPool的源码放出来:
public class Executors {
/**
* Creates a thread pool that reuses a fixed number of threads
* operating off a shared unbounded queue. At any point, at most
* {@code nThreads} threads will be active processing tasks.
* If additional tasks are submitted when all threads are active,
* they will wait in the queue until a thread is available.
* If any thread terminates due to a failure during execution
* prior to shutdown, a new one will take its place if needed to
* execute subsequent tasks. The threads in the pool will exist
* until it is explicitly {@link ExecutorService#shutdown shutdown}.
*
* @param nThreads the number of threads in the pool
* @return the newly created thread pool
* @throws IllegalArgumentException if {@code nThreads <= 0}
*/
public static ExecutorService newFixedThreadPool(int nThreads) {

本文探讨了Java中两种常见的线程池实现:FixedThreadPool和CachedThreadPool,通过源码分析揭示了它们可能导致的资源耗尽风险,并引用阿里巴巴代码规范建议避免使用Executors创建线程池,推荐使用ThreadPoolExecutor来更好地控制线程池的行为。
最低0.47元/天 解锁文章
1152

被折叠的 条评论
为什么被折叠?



