自定义线程工厂

说明

自定义线程工厂一般是为了给线程命名

自定义线程工厂的代码

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class CustomThreadFactory 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;

    public CustomThreadFactory(String namePrefix) {
        SecurityManager s = System.getSecurityManager();
        this.group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        if (namePrefix == null || namePrefix.isEmpty()) {
            this.namePrefix = "pool-" +
                    poolNumber.getAndIncrement() +
                    "-thread-";
        } else {
            if (!namePrefix.endsWith("-")) {
                this.namePrefix = namePrefix + "-";
            } else {
                this.namePrefix = namePrefix;
            }
        }
    }

    public CustomThreadFactory() {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        namePrefix = "pool-" +
                poolNumber.getAndIncrement() +
                "-thread-";
    }

    @Override
    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;
    }
}

使用自定义的线程工厂

return new ThreadPoolExecutor(3,
        3,
        60,
        TimeUnit.SECONDS,
        new LinkedBlockingQueue<>(20),
        new CustomThreadFactory("mdc-thread-pool"));
posted @ 2023-09-20 15:11  品书读茶  阅读(47)  评论(0编辑  收藏  举报