阿里开发规范—为何强制使用ThreadPoolExecutor创建线程池

阿里开发规范—为何强制使用ThreadPoolExecutor创建线程池

规范相关内容

【强制】线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,这

样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。

说明:Executors 返回的线程池对象的弊端如下:

1) FixedThreadPool 和 SingleThreadPool:

允许的请求队列的长度可能会堆积大量的请求,从而导致 OOM。

2) CachedThreadPool:

允许的创建线程数量为 Integer.MAX_VALUE,可能会创建大量的线程,从而导致 OOM。

源码

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

使用ThreadPoolExecutor创建线程池
public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             threadFactory, defaultHandler);
    }
// corePoolSize:核心池大小
// maximumPoolSize:线程池的最大线程数(指最大允许创建的线程数)
// keepAliveTime:空闲线程的存活时间
// TimeUnit:keepAliveTime时间的单位    
// workQueue:选择线程池中的任务队列
// threadFactory:线程工厂,用于创建线程
// defaultHandler:选择拒绝线程时,用那种拒绝策略

// 简单实现

@Service
@Slf4j
public class ExcelExportServiceImpl implements ExcelExportService {
     /**
     * 建议配合使用,自定义线程名称,便于查询管理
     * 定义线程工厂
     */
    private static ThreadFactory testThreadFactory = new ThreadFactoryBuilder().setNameFormat("excel-pool-%d").build();

    /**
     * 定义线程池
     */
    private static ExecutorService executorService = new ThreadPoolExecutor(10,10,0L, TimeUnit.MILLISECONDS,new 			LinkedBlockingDeque<>(1024),testThreadFactory);
	
    public static void main(String[] args) {
        for (int j =0;j<10;j++){
            executorService.execute(() ->{
                System.out.println(Thread.currentThread().getName());
            });
        }
        executorService.shutdown();
    }
}
// 输出结果
excel-pool-0
excel-pool-2
excel-pool-1
excel-pool-3
excel-pool-4
excel-pool-5
excel-pool-6
excel-pool-7
excel-pool-8
excel-pool-9
实际应用

EasyPoi实现网络图片的Excel导出功能:实现多线程处理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值