技术之海一望无际, 记忆长流永无止境|

丿似锦

园龄:7年3个月粉丝:33关注:3

🎀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().setNameFormatGuava 库中的一个方法,用于构建 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

结束

本文作者:丿似锦

本文链接:https://www.cnblogs.com/zktww/p/18558627

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   丿似锦  阅读(16)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起