Java Concurrency series of five: custom thread factory

problem

When we locate and troubleshoot field issues, usually want to clear the inside of the thread pool thread in the end is what the task is completed, you need to specify the name of the corresponding thread thread.

Solutions

When creating the thread pool, we can use a custom thread factory, the plant may indicate thread thread name, so that we can know when troubleshooting, what is the name of multi-threaded task here is to complete the concrete, to facilitate subsequent to locate the problem and troubleshooting.

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;
    }
}
Published 88 original articles · won praise 49 · Views 100,000 +

Guess you like

Origin blog.csdn.net/Diamond_Tao/article/details/103459618