package com.bawei.common.core.utils.thread;

import com.bawei.common.core.utils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;

/**
 * @author DongZl
 * @description: 线程池
 * @Date 2022-10-20 下午 02:33
 */
@Component
public class ThreadPool {

    private static ThreadPool threadPool;

    public static ThreadPool getThreadPool () {
        if (threadPool == null){
            threadPool = SpringUtils.getBean(ThreadPool.class);
        }
        return threadPool;
    }

    /**
     * 日志
     */
    private final static Logger log = LoggerFactory.getLogger(ThreadPool.class);

    /**
     * 创建数组型缓冲等待队列
     */
    private BlockingQueue<Runnable> bq = new ArrayBlockingQueue<Runnable>(20);
    /**
     * ThreadPoolExecutor（自定义线程池）:池中运行的线程数，允许最大挂起的线程数,线程销毁时间，线程销毁时间格式，队列保留
     */
    private ThreadPoolExecutor tpe = null;

    //定长线程池，支持定时及周期性任务执行——定期执行
    ScheduledExecutorService stp = null;

    @PostConstruct
    public void init(){
        long startTime = System.currentTimeMillis();
        log.info("线程池初始化开始");
        tpe = new ThreadPoolExecutor(2,
                50, 60, TimeUnit.SECONDS, bq);
        stp = Executors.newScheduledThreadPool(2);
        log.info("线程池初始化结束,耗时：[{}MS]", System.currentTimeMillis() - startTime);
    }

    /**
     * 执行
     */
    public void execute(Runnable runnable){
        tpe.execute(runnable);
    }

    /**
     * 延迟执行单位秒
     */
    public void delayExecute(long time, Runnable runnable){
        stp.schedule(runnable, time, TimeUnit.SECONDS);
    }


}
