一、 使用 ThreadPoolExecutor
自定义线程池
ThreadPoolExecutor
类提供了更灵活的线程池配置选项,可以自定义核心线程数、最大线程数、线程空闲时间、工作队列等参数。
import java.util.concurrent.*;
public class CustomThreadPool {
public static void main(String[] args) {
int corePoolSize = 5;//核心线程数
int maximumPoolSize = 10;//最大线程数
long keepAliveTime = 60L;//最大空闲等待时间
TimeUnit unit = TimeUnit.SECONDS;//单位,秒
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(100);//阻塞队列
ThreadFactory threadFactory = Executors.defaultThreadFactory();
RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
ThreadPoolExecutor executor = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
unit,
workQueue,
threadFactory,
handler
);
// 提交任务
for (int i = 0; i < 15; i++) {
final int index = i;
executor.execute(() -> {
System.out.println("Task " + index + " is running by " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
// 关闭线程池
executor.shutdown();
}
}
二、使用hutool工具
import cn.hutool.core.thread.ThreadUtil;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class HutoolCustomThreadPoolExample {
public static void main(String[] args) {
int corePoolSize = 5;
int maximumPoolSize = 10;
long keepAliveTime = 60L;
TimeUnit unit = TimeUnit.SECONDS;
int queueCapacity = 100;
// 使用 Hutool 创建自定义线程池
ExecutorService executor = ThreadUtil.newExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
unit,
queueCapacity
);
// 提交任务
for (int i = 0; i < 15; i++) {
final int index = i;
executor.execute(() -> {
System.out.println("Task " + index + " is running by " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
// 关闭线程池
executor.shutdown();
}
}
三、Java的Executors
工具类提供了几种常用的线程池创建方法
-
newFixedThreadPool:
- 创建一个具有固定数量线程的线程池。在这个线程池中,如果某个线程因为执行失败而结束,在后续的新任务到来时会创建一个新的线程来补充。适用于为了满足资源管理的需求,需要限制整个应用程序中并发线程数量的场景。
-
newSingleThreadExecutor:
- 创建一个只有一个线程的线程池,这个线程会顺序地执行任务队列中的任务。即使这个唯一的线程在执行过程中出现异常并终止,线程池也会重新创建一个新的线程来替代它继续处理后续的任务。适用于需要保证任务按提交顺序执行的场景。
-
newCachedThreadPool:
- 创建一个可根据需要创建新线程的线程池,但在以前构造的线程可用时将重用它们。对于每个任务,如果有空闲线程可以使用,则直接使用;如果没有空闲线程并且当前运行的线程数未超过最大限制(理论上是很大的值),则创建新的线程。在没有任务执行时(60秒内无新任务提交),它还会回收空闲的线程。适合于执行大量短期异步任务的小型程序或轻负载服务器。
-
newScheduledThreadPool:
- 创建一个支持定时及周期性任务执行的线程池。这意味着你可以安排任务在指定的延迟后运行,或者以固定的速率和时间间隔重复执行。这对于需要调度定时任务的场景非常有用,例如定期备份、数据统计等操作。