线程池工具类的封装

2023-05-16

了解更多学习 ThreadPoolExecutor
ThreadPool.java
package com.tool.me.thread;

import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPool {
    private static Map<String, ThreadPoolExecutor> map = new Hashtable<>();
    private ThreadPoolExecutor executor;
    /**
     * 阻塞任务队列数
     */
    private int wattingCount;
    /**
     * 线程池的名字,e.g:子系统的包名(com.tool.me)
     */
    @SuppressWarnings("unused")
    private String name;

    /**
     * 创建线程池
     * 
     * @param name
     *            线程池的名字,eg:子系统的包名(com.tool.me)
     * @param corePoolSize
     *            核心线程池大小 the number of threads to keep in the pool, even if
     *            they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize
     *            最大线程池大小 the maximum number of threads to allow in the pool
     * @param keepAliveTime
     *            线程池中超过corePoolSize数目的空闲线程最大存活时间 when the number of threads is
     *            greater than the core, this is the maximum time that excess
     *            idle threads will wait for new tasks before terminating.
     * @param unit
     *            keepAliveTime时间单位 the time unit for the {@code keepAliveTime}
     *            argument
     * @param workQueue
     *            阻塞任务队列 the queue to use for holding tasks before they are
     *            executed. This queue will hold only the {@code Runnable} tasks
     *            submitted by the {@code execute} method.
     */
    public ThreadPool(String name, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
            BlockingQueue<Runnable> workQueue) {
        synchronized (map) {
            this.name = name;
            this.wattingCount = workQueue.size();
            String key = buildKey(name, corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue.size(), "#");
            if (map.containsKey(key)) {
                executor = map.get(key);
            } else {
                executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
                map.put(key, executor);
            }
        }
    }

    /**
     * 创建线程池
     * 
     * @param name
     *            线程池的名字,eg:子系统的包名(com.tool.me)
     * @param corePoolSize
     *            核心线程池大小 the number of threads to keep in the pool, even if
     *            they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize
     *            最大线程池大小 the maximum number of threads to allow in the pool
     * @param keepAliveTime
     *            线程池中超过corePoolSize数目的空闲线程最大存活时间 when the number of threads is
     *            greater than the core, this is the maximum time that excess
     *            idle threads will wait for new tasks before terminating.
     * @param unit
     *            keepAliveTime时间单位 the time unit for the {@code keepAliveTime}
     *            argument
     * @param wattingCount
     *            阻塞任务队列数
     */
    public ThreadPool(String name, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
            int wattingCount) {
        synchronized (map) {
            this.name = name;
            this.wattingCount = (int) (wattingCount * 1.5);
            String key = buildKey(name, corePoolSize, maximumPoolSize, keepAliveTime, unit, wattingCount, "#");
            if (map.containsKey(key)) {
                executor = map.get(key);
            } else {
                executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit,
                        new LinkedBlockingQueue<Runnable>(this.wattingCount));
                map.put(key, executor);
            }
        }
    }

    /**
     * 组装map中的key
     * 
     * @param name
     *            线程池的名字,eg:子系统的包名(com.tool.me)
     * @param corePoolSize
     *            核心线程池大小 the number of threads to keep in the pool, even if
     *            they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize
     *            最大线程池大小 the maximum number of threads to allow in the pool
     * @param keepAliveTime
     *            线程池中超过corePoolSize数目的空闲线程最大存活时间 when the number of threads is
     *            greater than the core, this is the maximum time that excess
     *            idle threads will wait for new tasks before terminating.
     * @param unit
     *            keepAliveTime时间单位 the time unit for the {@code keepAliveTime}
     *            argument
     * @param workQueue
     *            阻塞任务队列 the queue to use for holding tasks before they are
     *            executed. This queue will hold only the {@code Runnable} tasks
     *            submitted by the {@code execute} method.
     * @param delimiter
     *            分割符
     */
    private String buildKey(String name, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
            int wattingCount, String delimiter) {
        StringBuilder result = new StringBuilder();
        result.append(name).append(delimiter);
        result.append(corePoolSize).append(delimiter);
        result.append(maximumPoolSize).append(delimiter);
        result.append(keepAliveTime).append(delimiter);
        result.append(unit.toString()).append(delimiter);
        result.append(wattingCount);
        return result.toString();
    }
    
    /**
     * 添加任务到线程池(execute)中
     * @param runnable the task to execute
     */
    public void execute(Runnable runnable) {
        checkQueneSize();
        executor.execute(runnable);
    }
    
    private void checkQueneSize() {
        while (getTaskSzie() >= wattingCount) {//如果线程池中的阻塞队列数 > wattingCount 则继续等待
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * Returns the number of elements in this collection.  If this collection
     * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
     * <tt>Integer.MAX_VALUE</tt>.
     *
     * @return the number of elements in this collection
     */
    public int getTaskSzie(){
        return executor.getQueue().size();
    }
}
ThreadPoolManager.java
package com.tool.me.thread;

import java.util.concurrent.TimeUnit;

public abstract class ThreadPoolManager {
    private ThreadPool executor = null;
    
    public ThreadPoolManager() {
        if(executor == null) {
            executor = new ThreadPool(getThreadPoolName(),corePoolSize(), maximumPoolSize(), keepAliveTime(), TimeUnit.SECONDS, wattingCount());
        }
    }
    
    public void execute(Runnable runnable) {
        executor.execute(runnable);
    }
    
    /**
     * @return name
     *            线程池名称 the String of pool name
     */
    protected abstract String getThreadPoolName();
    
    /**
     * @return corePoolSize
     *            核心线程池大小 the number of threads to keep in the pool, even if
     *            they are idle, unless {@code allowCoreThreadTimeOut} is set
     */
    protected int corePoolSize(){
        return 5;
    }
    
    /**
     * @return maximumPoolSize
     *            最大线程池大小 the maximum number of threads to allow in the pool
     */
    protected int maximumPoolSize(){
        return 10;
    }
    
    /**
     * @return wattingCount
     *            阻塞任务队列数
     */
    protected int wattingCount(){
        return 200000;
    }
    
    /**
     * @return keepAliveTime
     *            线程池中超过corePoolSize数目的空闲线程最大存活时间 when the number of threads is
     *            greater than the core, this is the maximum time that excess
     *            idle threads will wait for new tasks before terminating.
     */
    protected long keepAliveTime(){
        return 10;
    }
}
子系统创建类 继承ThreadPoolManager,配置参数信息
ViThreadPoolManager.java
package com.tool.me.thread;

/**
 * 当前类(子系统中定义的类)继承 ThreadPoolManager 类,设置相关参数
 */
public class ViThreadPoolManager extends ThreadPoolManager{
    private static ThreadPoolManager threadPool  = null;
    
    public synchronized static ThreadPoolManager getInstance() {
        if(threadPool == null) {
            threadPool = new ViThreadPoolManager();
        }
        return threadPool; 
    }
    
    @Override
    protected String getThreadPoolName() {
        return "com.tool.me.vi";
    }

    @Override
    protected int corePoolSize() {
        /**
         * 代码 设置返回值
         */
        return 10;
    }

    @Override
    protected int maximumPoolSize() {
        /**
         * 代码 设置返回值
         */
        return 20;
    }
}
使用线程池 main
    public static void main(String[] args) {
        ViThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                io();
            }
        });
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

线程池工具类的封装 的相关文章

  • Oracle数据库删除了数据如何恢复

    再操作数据库时 xff0c 有时候误删了数据或者更新数据时忘记设置更新条件 xff0c 要是这时候没有提交事务 xff0c 还可以执行回滚操作 要是这时候不小心提交了 xff0c 数据也是可以恢复的 我们只需要执行下面这句sql selec
  • (译)ASP.NET MVC Routing 概述

    ASP NET MVC Routing 概述 在本篇教程中 xff0c 你将会了解到 ASP NET MVC 中一个重要的组件 这个组件叫做 ASP NET Routing xff0c 它负责将客户端请求的路径映射到特定的一个类 Contr
  • eclipse中mysql java驱动的安装

    1 下载mysql connector java x x x zip 2 将压缩包中的mysql connector java x x x bin解压到eclipse中需要导入驱动的工程的根目录下 3 在eclipse中右键该工程选择属性
  • 如何使用gettext, po, mo制作多语言应用程序 (转)

    一 翻译档制作部分 1 制作 po 档 1 生成template文件 xgettext k o ui pref pot ui c pref pot head fuzzy msgid 34 34 msgstr 34 34 34 Project
  • (一) 进程调度

    进程调度算法有FIFO xff0c 优先数调度算法 xff0c 时间片轮转调度算法 xff0c 分级调度算法 xff0c 目前主要是考虑FIFO和优先数调度算法 xff08 静态优先级 xff09 输入 xff1a 进程流文件 xff0c
  • js跳转页面方法(转)

    lt span id 61 34 tiao 34 gt 3 lt span gt lt a href 61 34 javascript countDown 34 gt lt a gt 布丁足迹 秒后自动跳转 lt meta http equ
  • 缓存 ASP.NET 页的某些部分

    生成高性能 可缩放的 Web 应用程序最重要的因素之一是能够在首次请求项时将这些项存储在内存中 xff0c 不管它们是数据对象 页还是页的某些部分 可以将这些项缓存或存储在 Web 服务器上或请求流中的其他软件上 xff0c 如代理服务器或
  • TCP

    RFC 1323 TCP Extensions for High Performance RFC 2488 Enhancing TCP Over Satellite Channels using 传输层端口号定义 https www ian
  • zabbix-proxy安装

    注意 xff0c zabbix proxy的安装和zabbix server的安装不一样 不要混为一谈 xff0c 尤其是数据库的sql结构 rpm ivh http repo zabbix com zabbix 3 0 rhel 6 x8
  • konsole快捷键

    Tab xff1a 自动补全 Ctrl b xff1a 向前移动 xff0c 相当于 lt Left gt Ctrl f xff1a 向后移动 xff0c 相当于 lt Right gt Alt b xff1a 按词向前移动 Alt f x
  • docker中安装了RabbitMQ后无法访问其Web管理页面

    2019独角兽企业重金招聘Python工程师标准 gt gt gt 在官网找了 34 docker run d hostname my rabbit name some rabbit p 8080 15672 rabbitmq 3 mana
  • 网络数据包捕获函数库Libpcap安装与使用(非常强大)

    1 Libpcap简介 Libpcap是Packet Capture Libray的英文缩写 xff0c 即数据包捕获函数库 该库提供的C函数接口用于捕捉经过指定网络接口的数据包 xff0c 该接口应该是被设为混杂模式 这个在原始套接子中有
  • STM32F103控制两个步进电机按照一定转速比运动

    这个暑假没有回家 xff0c 在学校准备九月份的电子设计竞赛 今天想给大家分享一下STM32定时器控制两个步进电机按照一定速度比转动的问题 这次做的05年的电子设计竞赛题目 xff0c 运动悬挂系统 本实验是控制两个步进电机通过一个定滑轮用
  • Android 编程下的 Secret Code

    我们很多人应该都做过这样的操作 xff0c 打开拨号键盘输入 4636 等字符就会弹出一个界面显示手机相关的一些信息 xff0c 这个功能在 Android 中被称为 Android Secret Code xff0c 除了这些系统预置的
  • 用vim格式化代码

    格式化全文 xff1a gg 61 G 自动缩进当前行 xff1a 61 61 这个是原文节选 xff1a 14 6 How do I format indent an entire file You can format indent a
  • C# 之 反射性能优化3

    阅读目录 开始用Delegate优化反射的缺点用Delegate优化反射的优点用CodeDOM优化反射的优点如何用好CodeDOM xff1f 用CodeDOM优化反射的缺点能不能不使用委托 xff1f 根据反射密集程度选择优化方法Code
  • 基于用户行为的视频聚类方案

    在个性化推荐系统中 xff0c 通常是由挖掘物品属性来理解用户兴趣 xff0c 从而构建推荐模型 从用户行为去理解物品属性往往做得比较简单 xff0c 通常只是一些简单的标签统计 为了深入到用户行为去理解内容 xff0c 美拍利用用户的点击
  • .html文件调用接口示例

    直接在 html文件中请求接口的写法示例 span class hljs meta lt DOCTYPE html gt span span class hljs tag lt span class hljs name html span
  • mac os 环境下配置VMware Fusion虚拟机的互通网络

    安装环境 本文基于macOS Sierra 10 12 6系统为例 虚拟机应用VMware Fusion 10 1 3 系统Linux redhat 镜像rhel server 7 4 x86 64 dvd iso VMware Fusio
  • webpack的proxyTable无效的解决方案

    最近遇到这个需要单页访问跨域后台的问题 遇到了网上很多人说的 xff0c proxyTable无论如何修改 xff0c 都没效果的现象 经过几轮测试 xff0c 总结出一下几种解决方案 xff1a 1 xff08 非常重要 xff09 确保

随机推荐