package com.sckw.core.utils;

import java.util.concurrent.*;

/**
 * @author czh
 * @desc TODO
 * @date 2023/6/19
 */
public class AsyncThreadUtils {

    //CPU核心数
    private static final int corePoolSize = Runtime.getRuntime().availableProcessors();
    private static final int maximumPoolSize = corePoolSize * 2;
    private static final long keepAliveTime = 10;
    private static final TimeUnit keepAliveTimeUnit = TimeUnit.SECONDS;
    private static final BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(1024);
    private static final RejectedExecutionHandler rejectedHandler = new ThreadPoolExecutor.CallerRunsPolicy();

    /**
     * corePoolSize : 线程池核心线程数，最好默认CPU核心数
     * maximumPoolSize : 线程池最大线程数，最好是核心线程数的两倍，太多会引起线程切换
     * keepAliveTime : 大于核心线程数的空闲线程存活时间
     * keepAliveTimeUnit : 空闲线程存活时间的单位（秒、分钟、小时等等）
     * workQueue : 线程池有界队列，新任务没有可用线程处理时会把任务放到该队列中，等待被处理
     * rejectedHandler : 拒绝处理策略，默认直接丢弃并抛出异常-AbortPolicy，调用者线程直接处理-CallerRunsPolicy
     */
    private static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
            corePoolSize,
            maximumPoolSize,
            keepAliveTime,
            keepAliveTimeUnit,
            workQueue,
            rejectedHandler
    );

    /**
     * 直接提交任务，无返回值
     * @param task Runnable
     */
    public static void submit(Runnable task) {
        poolExecutor.submit(task);
    }

    /**
     * 提交任务，返回泛型结果
     * @param <T>
     * @return Future
     */
    public static <T> Future<T> submit(Callable<T> task) {
        return poolExecutor.submit(task);
    }

}
