java自定义线程池名称

背景:工作中有时候需要自定义线程池名称,以便于更好地定位问题。

分析

查看线程池核心类分析下:ThreadPoolExecutor

  • 线程池执行时会添加工作线程:
//如例子代码:
ExecutorService executorService =new ThreadPoolExecutor(5,5,1,
                TimeUnit.MINUTES,new LinkedBlockingDeque<>(),new NamedThreadFactory("测试"));//Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            executorService.execute(new AppTest2());
        }
        executorService.shutdown();
//1进去
 executorService.execute(new AppTest2());
//2 再跳到
addWorker(command, true)
//3 看下new Worker(firstTask);构造函数
Worker(Runnable firstTask) {
            setState(-1); // inhibit interrupts until runWorker
            this.firstTask = firstTask;
            this.thread = getThreadFactory().newThread(this);
        }
//4发觉创建名字在getThreadFactory().newThread(this);中,查看其构造函数:

DefaultThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                                  Thread.currentThread().getThreadGroup();
            namePrefix = "pool-" +
                          poolNumber.getAndIncrement() +
                         "-thread-";
        }
  • 所以最后很显然,新建线程池时new ThreadPoolExecutor()的7个参数中 ,ThreadFactory threadFactory参数就是负责给线程池命名。

  • 看到 ThreadFactory是一个接口,不难发现只要实现这个接口,把入参ThreadFactory改为自定义的实现类 就能自定义线程池名称。所以最后代码为:

public class AppTest2 implements Runnable{

    static class NamedThreadFactory  implements ThreadFactory {
        private final AtomicInteger poolNumber = new AtomicInteger(1);

        private final ThreadGroup threadGroup;

        private final AtomicInteger threadNumber = new AtomicInteger(1);

        public  final String namePrefix;
        NamedThreadFactory(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;
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService =new ThreadPoolExecutor(5,5,1,
                TimeUnit.MINUTES,new LinkedBlockingDeque<>()
                ,new NamedThreadFactory("测试"));
        for (int i = 0; i < 10; i++) {
            executorService.execute(new AppTest2());
        }
        executorService.shutdown();
    }

    @Override
    public void run() {
         System.out.println(Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

结果:
java自定义线程池名称_第1张图片

spring也为我们提供了自定义线程池的工具类:CustomizableThreadFactory,可以直接使用:

ThreadFactory springThreadFactory = new CustomizableThreadFactory("测试-pool-");
        ExecutorService executorService =new ThreadPoolExecutor(5,5,1,
                TimeUnit.MINUTES,new LinkedBlockingDeque<>(), springThreadFactory );
        for (int i = 0; i < 10; i++) {
            executorService.execute(new Test());
        }
        executorService.shutdown();

除此以外还有

  • Google guava 工具类 提供的 ThreadFactoryBuilder ,使用链式方法创建。
  • Apache commons-lang3 提供的 BasicThreadFactory

你可能感兴趣的:(并发编程,工作相关,源码,java,开发语言,后端)