手动创建线程池
2.2 使用可自定义线程名称的线程工厂
这个就简单多了,可以借助大名鼎鼎的谷歌开源工具库 Guava,首先引入如下依赖:
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.2-jre</version>
</dependency>
作者:IamHYN
链接:https://www.jianshu.com/p/c0f8d1e2b4eb
// 使用 ThreadFactoryBuilder 创建自定义线程名称的 ThreadFactory
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("hyn-demo-pool-%d").build();
ExecutorService threadPool=new ThreadPoolExecutor(2,5,
1L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
线程池中的常驻线程需要调用execute()方法执行
for (int i = 0; i < 11; i++) {
threadPool.execute(() -> {
要执行的任务
});
}
生产上常用的配置
private ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-call-runner-%d").build();
private ExecutorService taskExe = new ThreadPoolExecutor(10,20,200L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(),namedThreadFactory);
一、创建线程池的7个参数
1、corePoolSize线程池的核心线程数
2、maximumPoolSize能容纳的最大线程数
3、keepAliveTime空闲线程存活时间
4、unit 存活的时间单位
5、workQueue 存放提交但未执行任务的队列
6、threadFactory 创建线程的工厂类
7、handler 等待队列满后的拒绝策略
————————————————
版权声明:本文为CSDN博主「loulanyue」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:[https://blog.csdn.net/loulanyue/article/details/100166717](https://blog.csdn.net/loulanyue_/article/details/100166717)