package cc.smtweb.framework.core.systask;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Akmm at 2018/11/27 23:40
 * 通用线程池发放
 */
@Slf4j
public class SysThreadPool {
    //允许的最大线程池
    private static final int max_pool_size = 100;
    private static SysThreadPool instance = null;

    static {
        instance = new SysThreadPool();
    }

    public static SysThreadPool getInstance() {
        return instance;
    }

    private ThreadPoolExecutor threadPool;

    static class SysThreadFactory 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;

        SysThreadFactory() {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = "SysPool-" +
                    poolNumber.getAndIncrement() +
                    "-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 void addTask(SysThreadWorker worker) {
        if (threadPool == null) {
            threadPool = new ThreadPoolExecutor(2, max_pool_size,
                    60L, TimeUnit.SECONDS,
                    new ArrayBlockingQueue<Runnable>(100), new SysThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        }
        try {
            threadPool.execute(worker);
            log.debug("add task to SysPool success -> [PoolSize：" + threadPool.getPoolSize() + "，ActiveCount：" + threadPool.getActiveCount() + "，CompletedTaskCount：" + threadPool.getCompletedTaskCount() + "]");
        } catch (Exception e) {
            log.debug("add task to SysPool pools error：", e);
        }
    }

    //停止任务
    public void stop() {
        if (threadPool != null) threadPool.shutdown();
    }

    public static void main(String[] args) {
        for (int i = 1; i < 100; i++) {
            int j = i;
            SysThreadPool.getInstance().addTask(new SysThreadWorker() {
                @Override
                public void localWork() throws Exception {
                    Thread.sleep(1000);
                    log.debug("线程：[" + j + "]执行");
                }
            });
        }
    }
}
