参考DefaultThreadFactory重写一个自定义线程池名称的ThreadFactory
**目的:**当我们手动创建线程池的时候,也可以自定义当前线程池的名称,更好的区分,同时对相同的线程池,也可以进行分组显示。如上图,pool-开头的是默认的线程池名称,如果我们创建多个相同的线程池,也会有分组显示pool-1/2。
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author: tky
* @date: 2020/8/6
* @Description:
*/
public class NameCustomizedThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup threadGroup;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
NameCustomizedThreadFactory(String name) {
SecurityManager s = System.getSecurityManager();
threadGroup = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
if (null == name || "".equals(name.trim())) {
name = "pool";
}
namePrefix = name + "-" +
poolNumber.getAndIncrement() +
"-thread-";
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(threadGroup, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon()) {
t.setDaemon(false);
}
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
测试代码:
ThreadFactory threadFactory1 = new NameCustomizedThreadFactory("我的线程池");
ThreadFactory threadFactory2 = new NameCustomizedThreadFactory("我的线程池");
ThreadPoolExecutor newFixedThreadPool1 = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(100), threadFactory1);
ThreadPoolExecutor newFixedThreadPool2 = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(100), threadFactory2);
ExecutorService executorService1 = Executors.newFixedThreadPool(1);
ExecutorService executorService2 = Executors.newFixedThreadPool(1);
newFixedThreadPool1.execute(new MyThread());
newFixedThreadPool1.execute(new MyThread());
newFixedThreadPool1.execute(new MyThread());
newFixedThreadPool2.execute(new MyThread());
newFixedThreadPool2.execute(new MyThread());
newFixedThreadPool2.execute(new MyThread());