Java 线程池详解学习:FixedThreadPool,CachedThreadPool,ScheduledThreadPool...

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

Java常用的线程池有FixedThreadPool和CachedThreadPool,我们可以通过查看他们的源码来进行学习。


Java的源码下载参考这篇文章:Java源码下载和阅读(JDK1.8) - zhangpeterx的博客

在源码的目录java/util/concurrent下找到Executors.java文件查看源码。
里面提到的封装类有:
newScheduledThreadPoolnewSingleThreadScheduledExecutornewCachedThreadPoolnewSingleThreadExecutornewFixedThreadPoolnewWorkStealingPoolnewFixedThreadPool


我这里只把newFixedThreadPoolnewCachedThreadPool的源码放出来:

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) {
   
   
        
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值