线程池

创建线程池

调度线程池(ScheduledExecutorService)

引入依赖

1
2
3
4
5
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>

创建

1
2
3
4
5
6
// 需要引入commons-lang3依赖
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, new BasicThreadFactory
.Builder()
.namingPattern("example-schedule-pool-%d")
.daemon(true)
.build());

公共线程池(ExecutorService)

引入依赖

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.0.1-jre</version>
</dependency>

创建

1
2
3
4
5
6
7
8
9
10
// ThreadFactoryBuilder需要引入guava依赖
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
// 创建Common Thread Pool
ExecutorService pool = new ThreadPoolExecutor(5, 50, 3000L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(20),
namedThreadFactory,
new ThreadPoolExecutor.AbortPolicy());
// 执行任务
pool.execute(()-> System.out.println(Thread.currentThread().getName()));
pool.shutdown();//gracefully shutdown

参考网址

线程池构造函数各参数说明、参数间逻辑流程图_justry_deng的博客-CSDN博客