ThreadPoolUtil.java 1.9 KB
package cn.fw.freya.utils;

import cn.hutool.core.thread.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * @author wmy3969
 * @version 1.0
 * @date 2019/9/23 18:27
 * @Description 线程池工具类
 */
public class ThreadPoolUtil {

    /**
     * 先定义ThreadPoolExecutor类型的静态成员变量
     */
    public static ThreadPoolExecutor threadPool;

    /**
     * dcs获取线程池
     *
     * @return 线程池对象
     */
    public static ThreadPoolExecutor getThreadPool() {
        if (threadPool != null) {// 非首次调用该方法, threadPool不为null
            return threadPool;// threadPool对象不为空, 直接返回
        } else {
            synchronized (ThreadPoolUtil.class) {// threadPool == null, 加锁
                if (threadPool == null) {
                    threadPool = new ThreadPoolExecutor(
                            6,
                            12,
                            60,
                            TimeUnit.SECONDS,
                            new LinkedBlockingQueue<>(128),
                            new ThreadFactoryBuilder().setNamePrefix("capture-pool-").build(),
                            new ThreadPoolExecutor.DiscardPolicy());// 自行创建线程池, 并将创建好的线程池对象赋值给类的静态成员变量threadPool
                }
                return threadPool;// 将创建好的线程池对象返回
            }
        }
    }

    /**
     * 无返回值直接执行
     *
     * @param runnable
     */
    public static void execute(Runnable runnable) {
        getThreadPool().execute(runnable);
    }

    /**
     * 有返回值直接执行
     *
     * @param callable
     */
    public static <T> Future<T> submit(Callable<T> callable) {
        return getThreadPool().submit(callable);
    }

    /**
     * 关闭线程池
     */
    public static void shutdown() {
        getThreadPool().shutdown();
    }

}