zoukankan      html  css  js  c++  java
  • 单例线程池

    单例线程池

    直接上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());
                    }
                });

     欢迎提出建议探讨;

  • 相关阅读:
    Md5
    hdu 2569 彼岸
    调用系统相机相冊
    白盒測试
    HDU 1501
    IOS常见错误分析解决(一直更新) 你值得收藏-综合贴
    读“程序猿生存定律”笔记
    Halcon导出的cpp, VC++环境配置
    POJ 1260 Pearls (动规)
    hdoj-1856-More is better【并查集】
  • 原文地址:https://www.cnblogs.com/hb-liang/p/13862284.html
Copyright © 2011-2022 走看看