• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
axuuww
博客园    首页    新随笔    联系   管理    订阅  订阅
ThreadPoolUtils【手动创建线程】
package com.osdiot.cissync.util;

import java.util.concurrent.*;

/**
 * 线程池工具类
 *
 * @Author: Mr.LB
 * @Date: 2021-03-17 11:36
 * @Description: ThreadPoolUtils
 * 【手动创建线程池,规避资源耗尽的风险】
 * 说明:Executors返回的线程池弊端如下:
 * 1、FixedThreadPool 和 SingleThreadPool 允许的请求队列长度为 Integer.MAX_VALUE, 可能会堆积大量的请求, 从而导致OOM
 * 2、CachedThreadPool 和 ScheduledThreadPool 允许的创建线程数量为 Integer.MAX_VALUE, 可能会创建大量的线程, 从而导致OOM
 **/
public class ThreadPoolUtils {

    private static ExecutorService executorService;

    /**
     * @author Mr.LB
     * @date 2020/10/28 9:04
     * @description: 获取线程池实例
     **/
    private static ExecutorService build() {

        /**
         * isShutdown() 和 isTerminated() 的区别:
         * 线程池调用了shutdown()后,isShutdown()返回的就是true,
         * isTerminated()需要等待所有任务执行完毕才返回true,否则返回的是false
         **/
        if (null == executorService || executorService.isShutdown() || executorService.isTerminated()) {
            executorService = new ThreadPoolExecutor(50, 100, 30L,
                    TimeUnit.SECONDS, new ArrayBlockingQueue<>(256));
        }

        return executorService;
    }

    public static void execute(Runnable command) {

        build().execute(command);
    }

    public static <T> Future<T> submit(Callable<T> callable) {

        return build().submit(callable);
    }

}

posted on 2024-02-05 16:37  雁来月~十一  阅读(63)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3