线程池(二):Executors线程池 封装

本文详细探讨了Java中Executors提供的线程池类型,包括newFixedThreadPool、newSingleThreadExecutor、newCachedThreadPool、newScheduledThreadPool以及newSingleThreadScheduledExecutor,分析了它们的特性、工作队列和线程回收策略。建议在实际应用中根据需求选择合适的线程池实现,以优化系统资源的使用。
摘要由CSDN通过智能技术生成

Executors

禁止使用Executors创建线程池,而是通过ThreadPoolExecutor的方式创建,这样的处理方式能更加明确线程池的运行规则,避免资源耗尽的风险
1.workQueue 使用无界队列时
2.默认拒绝策略不是所有业务场景都适用

百度脑图 密码为 lNIX

java.util.concurrent.Executors里的方法
已有线程池创建

1.newFixedThreadPool固定容量

public static ExecutorService newFixedThreadPool(int nThreads) {
   
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
/**
     * Creates a thread pool that reuses a fixed number of threads
     * operating off a shared unbounded queue, using the provided
     * ThreadFactory to create new threads when needed.  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
     * @param threadFactory the factory to use when creating new threads
     * @return the newly created thread pool
     * @throws NullPointerException if threadFactory is null
     * @throws IllegalArgumentException if {@code nThreads <= 0}
     */    
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
   
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值