• 枚举实现线程池单例


      如题,系统需要一个线程池,在多处地方均可使用,考虑使用单例来保证线程池对象的唯一性。而单例实现手段目前最火的是枚举,那好吧,就用它了。直接看代码吧:

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    /**
     * 枚举单例
     */
    public enum ThreadPool {
        INSTANCE;
    
        // 线程池单例
        private final ExecutorService es;
    
        // 私有构造器
        private ThreadPool() {
            es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
        }
    
        // 公有方法
        public ExecutorService getInstance() {
            return es;
        }
    }

      超级简单,使用这个单例也超级简单:

                ThreadPool.INSTANCE.getInstance().execute(() -> {
                    for (int i = 0; i < order4Items.size(); i++) {
                        String orderId = order4Items.get(i);
                        saveOrderItems(orderId, merchant);
    
                        // 当请求数达到30或者30的倍数,等一分钟后再次请求
                        if ((i + 1) % 30 == 0) {
                            try {
                                Thread.sleep(60 * 1000);
                            } catch (InterruptedException e) {
                                LOGGER.error("--saveOrders-- error: {}, orderId: {}, sellerId: {}", e.getMessage(), orderId, merchant.getMerchantId());
                                continue;
                            }
                        }
                    }
                });
  • 相关阅读:
    ubuntu 12.04 安装 redis
    php 获取中文字符拼音首字母
    js 调整排序
    python 练习
    Configuring Locales
    missing locales
    clean code meaningful names
    ubuntu 12.04 支持中文----完胜版
    why add to http response.responseText
    不通过扩展名,去判断文件类型
  • 原文地址:https://www.cnblogs.com/wuxun1997/p/11097173.html
Copyright © 2020-2023  润新知