自定义java线程池_我的Java自定义线程池执行器

自定义java线程池

ThreadPoolExecutor是Java并发api添加的一项功能,可以有效地维护和重用线程,因此我们的程序不必担心创建和销毁线程,也不必关注核心功能。 我创建了一个自定义线程池执行程序,以更好地了解线程池执行程序的工作方式。

功能性:

  • 它维护一个固定的线程池,即使没有任务提交也创建线程并启动线程,而ThreadPoolExecutor根据需要创建线程,即,每当将可运行对象提交给池且线程数小于核心池大小时。
  • 在ThreadPoolExecutor中,我们提供了一个等待队列,当所有线程忙于运行现有任务时,新的可运行任务将在该队列中等待。 队列填满后,将创建最大线程池大小的新线程。 在MyThreadPool中,我将可运行对象存储在链接列表中,因此每个任务都将在列表中等待并且不受限制,因此在此不使用maxPoolSize。
  • 在ThreadPoolExecutor中,我们使用Future Objects从任务中获取结果,如果结果不可用,则future.get()方法将阻塞,或者使用CompletionService。 在MyThreadPoolExecutor中,我创建了一个名为ResultListener的简单接口,用户必须提供对此的实现,如他希望如何处理输出。 每个任务完成后,ResultListener将获得带有任务输出的回调,或者在发生任何异常的情况下将调用error方法。
  • 调用shutdown方法时,MyThreadPoolExecutor将停止接受新任务并完成剩余任务。
  • 与ThreadPoolExecutor相比,我提供了非常基本的功能,我使用了简单的线程机制,如wait(),notify(),notifyAll()和join()。
  • 在性能方面,它类似于ThreadPoolExecutor,在某些情况下好一些。 如果您发现任何有趣的结果或改进方法,请告诉我。
package com.util;import java.util.concurrent.Callable;/*** Run submitted task of {@link MyThreadPool} After running the task , It calls* on {@link ResultListener}object with {@link Output}which contains returned* result of {@link Callable}task. Waits if the pool is empty.* * @author abhishek* * @param */import java.util.concurrent.Callable;
/**
* Run submitted task of {@link MyThreadPool} After running the task , It calls
* on {@link ResultListener}object with {@link Output}which contains returned
* result of {@link Callable}task. Waits if the pool is empty.
*
* @author abhishek
*
* @param <V>
*/
public class MyThread<V> extends Thread {/*** MyThreadPool object, from which the task to be run*/private MyThreadPool<V> pool;private boolean active = true;public boolean isActive() {return active;}public void setPool(MyThreadPool<V> p) {pool = p;}/*** Checks if there are any unfinished tasks left. if there are , then runs* the task and call back with output on resultListner Waits if there are no* tasks available to run If shutDown is called on MyThreadPool, all waiting* threads will exit and all running threads will exit after finishing the* task*/public void run() {ResultListener<V> result = pool.getResultListener();Callable<V> task;while (true){task = pool.removeFromQueue();if (task != null){try{V output = task.call();result.finish(output);} catch (Exception e){result.error(e);}} else{if (!isActive())break;else{synchronized (pool.getWaitLock()){try{pool.getWaitLock().wait();} catch (InterruptedException e){// TODO Auto-generated catch blocke.printStackTrace();}}}}}}void shutdown() {active = false;}
}
package com.util;
import java.util.LinkedList;
import java.util.concurrent.Callable;
/**
* This class is used to execute submitted {@link Callable} tasks. this class
* creates and manages fixed number of threads User will provide a
* {@link ResultListener}object in order to get the Result of submitted task
*
* @author abhishek
*
*
*/
public class MyThreadPool<V> {private Object waitLock = new Object();public Object getWaitLock() {return waitLock;}/*** list of threads for completing submitted tasks*/private final LinkedList<MyThread<V>> threads;/*** submitted task will be kept in this list untill they run by one of* threads in pool*/private final LinkedList<Callable<V>> tasks;/*** shutDown flag to shut Down service*/private volatile boolean shutDown;/*** ResultListener to get back the result of submitted tasks*/private ResultListener<V> resultListener;/*** initializes the threadPool by starting the threads threads will wait till* tasks are not submitted** @param size* Number of threads to be created and maintained in pool* @param myResultListener* ResultListener to get back result*/public MyThreadPool(int size, ResultListener<V> myResultListener) {tasks = new LinkedList<Callable<V>>();threads = new LinkedList<MyThread<V>>();shutDown = false;resultListener = myResultListener;for (int i = 0; i < size; i++) {MyThread<V> myThread = new MyThread<V>();myThread.setPool(this);threads.add(myThread);myThread.start();}}public ResultListener<V> getResultListener() {return resultListener;}public void setResultListener(ResultListener<V> resultListener) {this.resultListener = resultListener;}public boolean isShutDown() {return shutDown;}public int getThreadPoolSize() {return threads.size();}public synchronized Callable<V> removeFromQueue() {return tasks.poll();}public synchronized void addToTasks(Callable<V> callable) {tasks.add(callable);}/*** submits the task to threadPool. will not accept any new task if shutDown* is called Adds the task to the list and notify any waiting threads** @param callable*/public void submit(Callable<V> callable) {if (!shutDown) {addToTasks(callable);synchronized (this.waitLock) {waitLock.notify();}} else {System.out.println('task is rejected.. Pool shutDown executed');}}/*** Initiates a shutdown in which previously submitted tasks are executed,* but no new tasks will be accepted. Waits if there are unfinished tasks* remaining**/public void stop() {for (MyThread<V> mythread : threads) {mythread.shutdown();}synchronized (this.waitLock) {waitLock.notifyAll();}for (MyThread<V> mythread : threads) {try {mythread.join();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
}
package com.util;/*** This interface imposes finish method * which is used to get the {@link Output} object * of finished task* @author abhishek** @param */public interface ResultListener {public void finish(T obj);public void error(Exception ex);}

您可以根据需要实现此类并返回并处理任务返回的结果。

package com.util;public class DefaultResultListener implements ResultListener{@Overridepublic void finish(Object obj) {}@Overridepublic void error(Exception ex) {ex.printStackTrace();}}

例如,此类将添加task返回的数字。

package com.util;import java.util.concurrent.atomic.AtomicInteger;/*** ResultListener class to keep track of total matched count* @author abhishek* * @param */
public class MatchedCountResultListenerimplements ResultListener{/*** matchedCount to keep track of the number of matches returned by submitted* task*/AtomicInteger matchedCount = new AtomicInteger();/*** this method is called by ThreadPool to give back the result of callable* task. if the task completed successfully then increment the matchedCount by* result count*/@Overridepublic void finish(V obj) {//System.out.println('count is '+obj);matchedCount.addAndGet((Integer)obj);}/*** print exception thrown in running the task*/@Overridepublic void error(Exception ex) {ex.printStackTrace();}/*** returns the final matched count of all the finished tasks* * @return*/public int getFinalCount() {return matchedCount.get();}
}

这是一个测试类,使用CompletionService和MyThreadPoolExecutor对循环运行简单

package test;import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;import com.util.DefaultResultListener;
import com.util.MyThreadPool;public class TestClass {public static void main(String[] args) throws InterruptedException {CompletionServicethreadService;ExecutorService service = Executors.newFixedThreadPool(2);threadService = new ExecutorCompletionService(service);long b = System.currentTimeMillis();for(int i =0;i<50000;i++){threadService.submit(new MyRunable (i));}service.shutdown();System.out.println('time taken by Completion Service ' + (System.currentTimeMillis()-b));DefaultResultListener result = new DefaultResultListener();MyThreadPoolnewPool = new MyThreadPool(2,result);long a = System.currentTimeMillis();int cc =0;for(int i =0;i<50000;i++){cc = cc+i;}System.out.println('time taken without any pool ' + (System.currentTimeMillis()-a));a= System.currentTimeMillis();for(int i =0;i<5000;i++){newPool.submit(new MyRunable (i));}newPool.stop();System.out.println('time taken by myThreadPool ' + (System.currentTimeMillis()-a));}}class MyRunable implements Callable{int index = -1;public MyRunable(int index){this.index = index;}@Overridepublic Integer call() throws Exception {return index;}}

参考: 我的JCG合作伙伴 Abhishek Somani在Java,J2EE和Server博客上的Java 自定义线程池执行程序 。

翻译自: https://www.javacodegeeks.com/2013/03/my-custom-thread-pool-executor-in-java.html

自定义java线程池

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/350538.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

es6方法过滤掉两个数组中对象id值相等的项

let arr1[{id:1,name:张三},{id:2,name:李四}] let arr2[{id:1,name:张三},{id:3,name:王五},{id:44,name:王柳},{id:45,name:王琦},] let addarr2.filter(item>!arr1.some(ele>ele.iditem.id)) console.log(add) const arr1 [{ id: 1, name: 网 }, { id: 2, name: 二位…

大尾和小尾

字节存放有大尾和小尾之分。如果对应数据的高字节存放在低地址就是大尾&#xff0c;反之&#xff0c;高字节存放在高地址的就是小尾。 比如 short int a 0x1234 大尾存放时&#xff1a; 偏移地址 存放内容 0x0000 0x12 0x0001 0x34 小尾存放&#xff1a; 偏移…

jedis使用_Redis的三个框架:Jedis,Redisson,Lettuce

Jedis api 在线网址&#xff1a;http://tool.oschina.net/uploads/apidocs/redis/clients/jedis/Jedis.htmlredisson 官网地址&#xff1a;https://redisson.org/redisson git项目地址&#xff1a;https://github.com/redisson/redissonlettuce 官网地址&#xff1a;https://le…

端到端BPM(带有DMN标记)

下周的红帽峰会即将成为有史以来最好的峰会之一&#xff01; 而且&#xff0c;如果您是Drools或jBPM的狂热者&#xff0c;您会很忙 &#xff1a;Signavio和Red Hat之间的合作伙伴关系是我们为您准备的另一个顶级演讲。 邓肯道尔&#xff08;Duncan Doyle&#xff09;和汤姆德贝…

pycharm写python字典_pythonpycharm安装基础语法

1.python安装安装python3&#xff0c;建议安装python3.7&#xff0c;不要安装python2安装时需要注意的地方&#xff1a;安装完成后&#xff0c;验证python是否安装成功&#xff0c;在cmd下输入python&#xff0c;出现python的版本则表明安装成功验证pip是否安装成功&#xff0c…

模板库 | 销售管理类报表,邀您提反馈

“葡萄城报表模板库是一款免费的报表制作、学习和参考工具&#xff0c;包含了超过 200 张高质量报表模板&#xff0c;涵盖了 16 大行业和 50 多种报表类型&#xff0c;为 30 余万报表开发者提供价值参考。” 近期&#xff0c;葡萄城推出了“寻找真正的报表大师”活动&#xff0…

矩阵的逆、伪逆

1、矩阵的逆 定义&#xff1a; 设A是数域上的一个n阶方阵&#xff0c;若在相同数域上存在另一个n阶矩阵B&#xff0c;使得&#xff1a; ABBAI。 则我们称B是A的逆矩阵&#xff0c;而A则被称为可逆矩阵。 可逆条件&#xff1a; A是可逆矩阵的充分必要条件是&#xff0c;即可…

PLSQL登录报错ORA-12154

https://blog.csdn.net/naomi_qing/article/details/79583453 转载于:https://www.cnblogs.com/2016-cxp/p/10878952.html

python将dataframe导出为csv_python将dataframe转换为csv,为每列导出一个格式独特的文本文件...

我正在Win7 64位上使用Python2.7.7和熊猫。我的输入数据最初是以空格分隔的&#xff0c;右对齐的。我现在有数据作为熊猫数据帧&#xff0c;我导出为一个csv。我想写一个空格分隔的右对齐文本文件。列有字符串、int和float。我试图用这个来格式化其中一个列&#xff1a;df_fg[M…

jax-rs/jersey_在Oracle Cloud上的Prime-UI,JAX-RS和Jersey和Gson

jax-rs/jersey如今&#xff0c;Oracle云无处不在。 最初&#xff0c;拉里&#xff08;Larry&#xff09;否认在很长一段时间内都需要云&#xff0c;并且在去年的开放世界&#xff08;Open World&#xff09;之后就发布了一些非常早的公告&#xff0c;而且可用性很差&#xff0c…

OpenCV copyMakeBorder()来拓展边界

使用OpenCV提供的函数copyMakeBorder()来拓展边界&#xff0c;其原型如下 void copyMakeBorder( InputArray src, OutputArray dst,int top, int bottom, int left, int right, int borderType,const Scalar& value Scalar())​ src&#xff1a;输入的数组。 dst&…

Flutter-现有iOS工程引入Flutter

前言 Flutter 是一个很有潜力的框架&#xff0c;但是目前使用Flutter的APP并不算很多&#xff0c;相关资料并不丰富&#xff0c;介绍现有工程引入Flutter的相关文章也比较少。项目从零开始&#xff0c;引入Flutter操作比较简单&#xff0c;但是现有工程引入Flutter 需要费很多精…

python有什么隐藏功能_Python的隐藏功能

文章目录Python编程语言的鲜为人知的但有用的功能是什么&#xff1f;尝试限制Python核心的答案。每个答案的一个功能给出一个功能的例子和简短描述&#xff0c;而不仅仅是文档的链接。使用标题作为第一行标记该功能。Quick links to answers:Chaining comparison operators:>…

Spring Boot –适合您的靴子!

您需要一点弹簧吗&#xff1f; 厌倦了所有繁琐的Web服务器并部署WAR文件&#xff1f; 好吧&#xff0c;你很幸运。 Spring Boot对构建可用于生产的Spring应用程序持坚定态度。 Spring Boot倾向于使用约定而非配置&#xff0c;它旨在使您尽快启动并运行。 在此博客中&#xff0…

OpenCV 像素的读取与操作

像素读取和操作 1. 利用cv::Mat的at函数&#xff0c;直接访问具体地址 void get_setImagePixel(char *imagePath, int x, int y){// Mat image imread(imagePath , 0);Mat image imread(imagePath, 1);//得宽高int w image.cols;int h image.rows;int channels image.c…

[http]HTTP状态码含义

HTTP状态码 当浏览者访问一个网页时&#xff0c;浏览者的浏览器会向网页所在服务器发出请求。当浏览器接收并显示网页前&#xff0c;此网页所在的服务器会返回一个包含HTTP状态码的信息头&#xff08;server header&#xff09;用以响应浏览器的请求。 HTTP状态码的英文为HTTP …

不等式约束的拉格朗日乘数法_Abaqus血管支架仿真|接触约束执行方式

根据支架的建模基础、几何和网格划分、单元选择、材料和截面属性、分析步设置、载荷接触和约束、收敛调整&#xff0c;以及后处理、参数优化等内容。接着Abaqus血管支架仿真|建模基础、Abaqus血管支架仿真|几何和网格划分、Abaqus血管支架仿真|单元选择、Abaqus血管支架仿真|材…

OpenCV形态学运算

1.OpenCV形态学运算morphologyEx&#xff08;开运算 、闭运算 、形态学梯度 、顶帽运算 、黑帽运算 、腐蚀运算 、膨胀运算 、击中击不中运算&#xff09; void cv::morphologyEx (InputArray src,OutputArray dst,int op,InputArray kernel,Point anchor Point(-1,-1),int …

python判断成绩等级_Python计算山东新高考选考科目卷面原始成绩为等级成绩

原标题&#xff1a;Python计算山东新高考选考科目卷面原始成绩为等级成绩图书详情&#xff1a;配套资源&#xff1a;用书教师可以免费获取教学大纲、教案、课件、源码、习题答案、课堂管理与考试系统。山东省新高考政策33中&#xff0c;考生必考科目有语文、数学、英语&#xf…

java web ee_Java EE 6 Web配置文件。 在云上。 简单。

java web eeJava SE还可以。 Java EE是邪恶的。 这就是我一直想的。 好吧&#xff0c;现在不再了。 让我分享我的经验。 几周前&#xff0c;我开始考虑将旧版spring hibernate tomcat应用程序移植到新平台上&#xff1a; SAP NetWeaver云 。 我知道您在极客那里的想法&…