【多线程】自定义线程池中执行线程的统一名称

本文介绍如何在创建线程池时使用ThreadFactory参数来自定义线程名称,通过参考Executors的默认线程工厂实现,使得线程在执行时显示统一的前缀MY_CUSTOM_NAME。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新建线程池的时候,可以传入ThreadFactory作为参数 

Executors.newCachedThreadPool(ThreadFactory threadFactory)

可以参考Executors自带的默认线程工厂类的实现

Executors.defaultThreadFactory();
 static class NameableThreadFactory implements ThreadFactory{
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        NameableThreadFactory(String name) {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = name+"-pool-" +
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

新建线程池时传入自定义名称即可

ExecutorService threadPool = Executors.newCachedThreadPool(new NameableThreadFactory("MY-CUSTOM-NAME"));

for(int i=0;i<10;i++) {
    threadPool.execute(() -> {
        System.out.println(Thread.currentThread().getName());
    });
}

执行结果:

MY-CUSTOM-NAME-pool-1-thread-1
MY-CUSTOM-NAME-pool-1-thread-2
MY-CUSTOM-NAME-pool-1-thread-3
MY-CUSTOM-NAME-pool-1-thread-4
MY-CUSTOM-NAME-pool-1-thread-5
MY-CUSTOM-NAME-pool-1-thread-2
MY-CUSTOM-NAME-pool-1-thread-5
MY-CUSTOM-NAME-pool-1-thread-1
MY-CUSTOM-NAME-pool-1-thread-4
MY-CUSTOM-NAME-pool-1-thread-3

可以看见名称中带有我们传入的前缀MY_CUSTOM_NAME

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值