我是靠谱客的博主 冷静嚓茶,这篇文章主要介绍阿里开发规范—为何强制使用ThreadPoolExecutor创建线程池,现在分享给大家,希望可以做个参考。

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

规范相关内容

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

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

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

1) FixedThreadPool 和 SingleThreadPool:

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

2) CachedThreadPool:

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

源码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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创建线程池

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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导出功能:实现多线程处理

最后

以上就是冷静嚓茶最近收集整理的关于阿里开发规范—为何强制使用ThreadPoolExecutor创建线程池的全部内容,更多相关阿里开发规范—为何强制使用ThreadPoolExecutor创建线程池内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(98)

评论列表共有 0 条评论

立即
投稿
返回
顶部