package com.base.core;

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

public class AccessThreadFactory implements ThreadFactory {

    private static final AtomicInteger poolNumber = new AtomicInteger(1);

    private final ThreadGroup threadGroup;

    private final AtomicInteger threadNumber = new AtomicInteger(1);

    private final String namePrefix;

    public AccessThreadFactory(){
        SecurityManager securityManager = System.getSecurityManager();
        threadGroup = securityManager!=null?securityManager.getThreadGroup():Thread.currentThread().getThreadGroup();
        namePrefix = "pool-" + poolNumber.getAndIncrement() + "-AccessThread-";
    }


    @Override
    public Thread newThread(Runnable runnable) {
        Thread thread = new Thread(threadGroup, runnable, namePrefix+threadNumber.getAndIncrement(),0);

        if (thread.isDaemon()){
            thread.setDaemon(false);
        }
        //设置优先级，可以改
        if (thread.getPriority()!=Thread.NORM_PRIORITY){
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }
}
