package com.sckw.contract.factory;

import cn.hutool.core.thread.NamedThreadFactory;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author czh
 * @desc 异步工厂
 * @date 2023/6/19
 */
public class AsyncFactory {

    private AsyncFactory() {}

    /**
     * 全局访问点
     */
    public static void execute(Runnable runnable) {
        ThreadPoolExecutorHolder.THREAD_POOL_EXECUTOR.execute(runnable);
    }

    /**
     * 静态内部类创建实例(单例)
     */
    private static class ThreadPoolExecutorHolder {
//        static final int CPU = Runtime.getRuntime().availableProcessors();
        static final int CORE_POOL_SIZE = 10;
        static final int MAXIMUM_POOL_SIZE = 15;
        static final long KEEP_ALIVE_TIME = 1L;
        static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
        static final int MAX_QUEUE_NUM = 1024;

        //static变量只会初始化一次
        public static final ThreadPoolExecutor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(
                CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, TIME_UNIT,
                new LinkedBlockingQueue<>(MAX_QUEUE_NUM),
                new NamedThreadFactory("ThreadPoolExecutorFactory-", false),
                new ThreadPoolExecutor.AbortPolicy());
    }


}
