新建线程池的时候,可以传入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