🎀Java线程池创建

💖简介
Java 手动创建线程池
📖代码
package com.zk.app.utils;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @program: ZK
* @description:
* @author: zuokun
* @create: 2024-11-20 15:44
**/
public class ThreadPoolUtils {
private static volatile ExecutorService testExecutor;
public static ExecutorService getTestExecutor() {
if(testExecutor == null){
synchronized (ThreadPoolUtils.class){
if(testExecutor == null){
testExecutor = new ThreadPoolExecutor(10, 20, 10,
java.util.concurrent.TimeUnit.SECONDS,
new ArrayBlockingQueue<>(100),
new ThreadFactoryBuilder().setNameFormat("test-pool-%d").build(),
new ThreadPoolExecutor.CallerRunsPolicy());
}
}
}
return testExecutor;
}
}
ThreadFactoryBuilder().setNameFormat是Guava库中的一个方法,用于构建ThreadFactory实例。这个ThreadFactory可以用来创建新的线程,并且可以设置线程的名称格式。
⭐使用
@Test
public void poolTest() {
for (int i = 0; i < 10; i++) {
ThreadPoolUtils.getTestExecutor().submit(() -> {
System.out.println(Thread.currentThread().getName());
});
}
}
🌟结果
test-pool-0
test-pool-3
test-pool-2
test-pool-1
test-pool-4
test-pool-5
test-pool-6
test-pool-7
test-pool-8
test-pool-9
结束

浙公网安备 33010602011771号