package com.jianshui.queue.threadpoll;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author 巩权林
 * @Date 2021-11-25 9:55
 **/
public class RedisQueueThreadPool {

    protected final Logger log = LoggerFactory.getLogger(RedisQueueThreadPool.class);

    // 线程池创建类
    private ThreadPoolExecutor mexecutor;

    private static RedisQueueThreadPool instance;

    // 获取java虚拟机最大可用
    private final int availableProcessor = Runtime.getRuntime().availableProcessors();


    public RedisQueueThreadPool(int coreNum) {
        if (mexecutor == null) {
            // 用单例模式创建线程池，保留2个核心线程，最多线程为CPU个数的2n+1的两倍.
            mexecutor = new ThreadPoolExecutor(coreNum == 0 ? 3 : coreNum, coreNum, 0L,
                    TimeUnit.MILLISECONDS,
                    new LinkedBlockingDeque<Runnable>(),
                    Executors.defaultThreadFactory(),
                    new ThreadPoolExecutor.AbortPolicy());

        }

    }


    public static RedisQueueThreadPool getInstance(int coreNum) {
        Logger log = LoggerFactory.getLogger(RedisQueueThreadPool.class);
        if (instance == null) {
            instance = new RedisQueueThreadPool(coreNum);
            log.info("【redis队列】RedisQueueThreadPool线程池已经开启");
        }
        return instance;
    }

    public void executor(Runnable runnable) {
        if (null == runnable) {
            return;
        }
        mexecutor.execute(runnable);
    }

    public void getInfo() {
        if (null == mexecutor) {
            return;
        }
        int queueSize = mexecutor.getQueue().size();
        log.info("【redis队列】当前排队线程数：" + queueSize);

        int activeCount = mexecutor.getActiveCount();
        log.info("【redis队列】当前活动线程数：" + activeCount);

        long completedTaskCount = mexecutor.getCompletedTaskCount();
        log.info("【redis队列】执行完成线程数：" + completedTaskCount);

        long taskCount = mexecutor.getTaskCount();
        log.info("【redis队列】总线程数：" + taskCount);
    }

    public void destroy() {
        if (mexecutor != null) {
            // 终止线程池
            mexecutor.shutdown();
        }
    }
}
