单例线程池

单例线程池

直接上demo 

package com.feihe.train.traincommon.util;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * Description: ThreadPoolUtil <br>
 *
 * @author Mr.Liang
 * Date: 2020/10/22 19:09 <br>
 */
public class ThreadPoolUtil {

    private volatile static ExecutorService pool = null;

    private static ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("pool-%d").build();

    /**
     * 获取单实例线程池
     * corePoolSize 核心池大小
     * maximumPoolSize 最大线程数
     * keepAliveTime    存活时间(默认60秒回收部分空闲的线程)
     * TimeUnit.SECONDS 时间单位
     * 在执行任务之前用于保留任务的队列。
     * 执行程序*创建新线程时要使用的工厂
     * 处理程序当执行被阻止时要使用的处理程序*因为达到了线程界限和队列容量
     *
     * @return
     */
    public static ExecutorService getThreadPoolExecutor() {
        if (pool == null) {
            synchronized (ThreadPoolUtil.class) {
                if (pool == null || pool.isShutdown()) {
                    pool = new ThreadPoolExecutor(20, 30,
                            60L, TimeUnit.SECONDS,
                            new LinkedBlockingQueue<Runnable>(1024), threadFactory, new ThreadPoolExecutor.AbortPolicy());
                }
            }
        }
        return pool;
    }

}

  

使用submit 和使用execute 区别就不解释了

 

            ThreadPoolUtil.getThreadPoolExecutor().submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {

                    System.out.println(Thread.currentThread().getName());
                    return null;
                }
            });
            ThreadPoolUtil.getThreadPoolExecutor().execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });

 欢迎提出建议探讨;

posted @ 2020-10-23 09:20  Mr、Liang  阅读(554)  评论(0编辑  收藏  举报