问题

我们在排查和定位现场问题时,通常希望明确这个线程池里面的线程到底是完成什么的什么任务,所以需要指定对应线程的线程名称。

解决方式

在创建线程池的时候,我们可以使用自定义的线程工厂,该线程工厂中可以指明线程名称,这样我们在排查问题时就可以知道,此处的多线程具体完成的任务名称是什么,方便进行后续的问题定位与排查。

public class CustomThreadFactory implements ThreadFactory {
   


    /** * 线程号 */
    private final AtomicInteger threadNum = new AtomicInteger(1);

    /** * 线程名称 */
    private String threadName;

    public DetectorThreadFactory(String threadName) {
   
        this.threadName = threadName + "-";
    }

    @Override
    public Thread newThread(Runnable r) {
   
        Thread thread = new Thread(r);
        thread.setName(threadName + threadNum.getAndIncrement());
        return thread;
    }
}