添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

线程池线程重命名

使用场景

在工作中使用线程池,万一线程抛出异常了,日志不好记录到底是哪个线程池抛出的异常;所以为了方便排查,给线程池的线程自定义命名,主要方法就是重写生产线程工厂的命名方法。下面代码示范

集成线程工厂重写

public class NamedThreadFactory 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;
    NamedThreadFactory(String name) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        if (null == name || name.isEmpty()) {
            name = "pool";
        namePrefix = name + "-thread-";
    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;
}

创建一个线程池来测试一下

public class Test {
    public static void main(String[] args) throws MalformedURLException, InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10,
                                            TimeUnit.SECONDS,
                                            new ArrayBlockingQueue<>(10),
                                            new NamedThreadFactory("xxx业务的线程池"));
        for (int i=0;i<10;i++){
            threadPoolExecutor.execute(()->{
                System.out.println(Thread.currentThread().getName());