博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
线程池工具类的封装
阅读量:6607 次
发布时间:2019-06-24

本文共 7779 字,大约阅读时间需要 25 分钟。

了解更多学习 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
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
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
(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
Integer.MAX_VALUE elements, returns *
Integer.MAX_VALUE. * * @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();			}		});	}复制代码

转载于:https://juejin.im/post/5c501e2d6fb9a049db7388c2

你可能感兴趣的文章
【转】关于大型网站技术演进的思考(十二)--网站静态化处理—缓存(4)
查看>>
积跬步,聚小流------Bootstrap学习记录(1)
查看>>
HDUPhysical Examination(贪心)
查看>>
HTML5 FileAPI
查看>>
使用tdcss.js轻松制作自己的style guide
查看>>
SecureCRTPortable.exe 如何上传文件
查看>>
C++中public、protected及private用法
查看>>
苹果公司的产品已用完后门与微软垄断,要检查起来,打架!
查看>>
顶级的JavaScript框架、库、工具及其使用
查看>>
AYUI -AYUI风格的 超美 百度网盘8.0
查看>>
简明 Python 教程
查看>>
用MPMoviePlayerController做在线音乐播放
查看>>
Java查找算法——二分查找
查看>>
如何构建微服务架构
查看>>
【前端笔记】彻底理解变量与函数的声明提升
查看>>
Android 反编译利器,jadx 的高级技巧
查看>>
二叉搜索树(递归实现)
查看>>
Spring Retry重试机制
查看>>
Android官方架构组件LiveData: 观察者模式领域二三事
查看>>
[Android组件化]组件化数据分享
查看>>