package com.storlead.framework.common.thread;


import java.util.List;
import java.util.concurrent.*;

/**
 * @program: sp-project-system
 * @description: 线程池工具类
 * @author: chenkq
 * @create: 2021-09-13 08:55
 */
public class ThreadPoolUtil {
    /**
     * 核心线程池的数量，同时能够执行的线程数量
     */
    private final static int corePoolSize  = Runtime.getRuntime().availableProcessors() * 2 + 1;
    /**
     * 最大线程池数量，表示当缓冲队列满的时候能继续容纳的等待任务的数量
     */
    private final static int maxPoolSize  = corePoolSize;
    /**
     * 存活时间
     */
    private final static long keepAliveTime = 60L;
    private final static TimeUnit unit = TimeUnit.SECONDS;

    /**
     * 线程等待队列
     */
    private static LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(2000);



    /**
     * 线程池对象
     */
    private static ThreadPoolExecutor threadExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize,
            keepAliveTime, unit, queue, new ThreadPoolExecutor.AbortPolicy());

    public static ThreadPoolExecutor getThreadExecutor() {
        return threadExecutor;
    }


    /**
     * 向线程池提交一个任务,返回线程结果
     * @param r
     * @return
     */
    public static Future<?> submit(Callable<?> r) {
        return threadExecutor.submit(r);
    }

    /**
     * 向线程池提交一个任务,返回线程结果
     * @param rs
     * @return
     */
    public static List<Future<?>> submits(List rs) {
        try {
            List list = threadExecutor.invokeAll(rs);
            return list;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 向线程池提交一个任务，不关心处理结果
     * @param r
     */
    public static void execute(Runnable r) {
        threadExecutor.execute(r);
    }

    /** 获取当前线程池线程数量 */
    public static int getSize() {
        return threadExecutor.getPoolSize();
    }

    /** 获取当前活动的线程数量 */
    public static int getActiveCount() {
        return threadExecutor.getActiveCount();
    }
}

