- 浏览: 10765 次
最新评论
转载地址:http://www.ibm.com/developerworks/cn/java/l-threadPool/#icomments
1. 任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行。
2. 工作线程(WorkThread): 线程池中线程
3. 线程池ThreadPool
4. 线程池管理器(ThreadPoolManager):用于创建并管理线程池
1. 任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行。
/** * <p>Title: </p> * <p>Description: use to test thread pool</p> * <p>Copyright: Copyright (c) 2002</p> * <p>Company: </p> * * @author xingyong * * @version 1.0 */ public interface Task { /** * set status of task . * @param flag */ public void setEnd(boolean flag) ; /** * start task * @throws java.lang.Exception */ public abstract void startTask() throws Exception; /** * end tast * @throws java.lang.Exception */ public abstract void endTask() throws Exception; /** * get status of task * @return boolean */ public boolean isEnd() ; }
2. 工作线程(WorkThread): 线程池中线程
import java.io.PrintStream; import java.util.Vector; /** * <p>Title: </p> * <p>Description: use to test thread pool</p> * <p>Copyright: Copyright (c) 2002</p> * <p>Company: </p> * * @author xingyong * * @version 1.0 */ public class WorkThread extends Thread { public int threadNum; private boolean flag; private Vector taskVector; private Task task; /** * @param vector * @param i */ public WorkThread(java.util.Vector vector, int i) { flag = true; threadNum = i; taskVector = vector; //hide entry here super.start(); } public void run() { while(flag && taskVector != null) { synchronized(taskVector) { while(taskVector.isEmpty() && flag) try { taskVector.wait(); } catch(Exception exception) { } try { task = (Task)taskVector.remove(0); } catch(Exception ex) { task = null; } if(task == null) continue; } try { task.setEnd(false); task.startTask(); } catch(Exception ex) { ex.printStackTrace(); } try { if(!task.isEnd()) { task.setEnd(true); task.endTask(); } } catch(Exception ex) { ex.printStackTrace(); } }//end of while } public void closeThread() { flag = false; try { if(task != null) task.endTask(); } catch(Exception exception) { exception.printStackTrace(); } synchronized(taskVector) { taskVector.notifyAll(); } } }
3. 线程池ThreadPool
/** * <p>Title: </p> * <p>Description: use to test thread pool</p> * <p>Copyright: Copyright (c) 2002</p> * <p>Company: </p> * * @author xingyong * * @version 1.0 *note: this test program refers to Tarak Modi's test structure */ public class TestThreadPool { private ThreadPoolManager threadPoolManager = null; public Object testlock = new Object(); public int count = 0 ; int jobsNumber = 200; int sizeOfThreadPool = 20; int debug = 2; public TestThreadPool(int threadPoolSize,int jobsNum) { //System.out.println("size: "+sizeOfThreadPool+" jobs: "+jobsNumber); sizeOfThreadPool = threadPoolSize; jobsNumber = jobsNum; long timeNoPool = 0; long timePool = 0; count = 0; System.err.println("Begin of testing strategy -- no pool"); long start = System.currentTimeMillis(); try { for(int i=0; i<jobsNumber ; i++) { CalculationTaskTest calculationTask = new CalculationTaskTest(); new Thread(calculationTask).start(); } } catch (OutOfMemoryError er) { System.out.println("No pool :OutOfMemoryError"); } catch (Exception ex) { ex.printStackTrace(); } sleepToWait(5); if(debug > 3) System.out.println("no pool time:" + (System.currentTimeMillis() - start)); timeNoPool = System.currentTimeMillis() - start; System.err.println("End of no pool test"); count = 0; //start = System.currentTimeMillis(); System.err.println("Begin of creating pool"); threadPoolManager = new ThreadPoolManager(sizeOfThreadPool); System.err.println("End of creating pool"); System.err.println("Begin of testing the strategy -- pool"); //without the time for creating pool start = System.currentTimeMillis(); try { for(int i=0; i<jobsNumber ; i++) { CalculationTaskTest calculationTaskTest = new CalculationTaskTest(); threadPoolManager.addTask(calculationTaskTest); } } catch (OutOfMemoryError er) { System.out.println("pool :OutOfMemoryError"+" "+sizeOfThreadPool+" "+jobsNumber); } catch (Exception ex) { ex.printStackTrace(); } sleepToWait(5); if(debug > 3) System.out.println("pool time:" + (System.currentTimeMillis() - start)); timePool = System.currentTimeMillis() - start; System.err.println("End of thread pool test"); System.out.println("without pool: "+timeNoPool+ " with pool: "+timePool); System.exit(0); } public void sleepToWait(long l) { while(true) { synchronized(testlock) { if( count == jobsNumber ) return; } try { //you can change it to wait end of all tasks Thread.sleep(l); } catch (Exception ex) { } } } public static void main(String[] args) { int poolSize = 20; int jobs= 200; if( args.length < 2 ) { System.err.println("Usage: java TestThreadPool " + "<Size of ThreadPool> <jobs> "); System.exit(-1); } try { poolSize = Integer.parseInt(args[0]); jobs = Integer.parseInt(args[1]); } catch (Exception ex) { System.out.println("Please input integer."); System.exit(-1); } new TestThreadPool(poolSize,jobs); } private class CalculationTaskTest implements Task,Runnable { private boolean isEnd = true; public CalculationTaskTest() { isEnd = true; } public void setEnd(boolean flag) { /**@todo: Implement this Task method*/ //throw new java.lang.UnsupportedOperationException("Method setEnd() not yet implemented."); isEnd = flag; } public void run() { int i = 1; int r = 1; //System.err.println("r:"+r); try { //you can change this line to simulate something for(int ii=0;ii<100;ii++) r = r+i*i; } catch (Exception ex) { } synchronized(testlock) { count++; } } public void startTask() throws Exception { /**@todo: Implement this Task method*/ //throw new java.lang.UnsupportedOperationException("Method startTask() not yet implemented."); //System.err.print("use pool"); run(); } public void endTask() throws Exception { /**@todo: Implement this Task method*/ //throw new java.lang.UnsupportedOperationException("Method endTask() not yet implemented."); //free resource here } public boolean isEnd() { /**@todo: Implement this Task method*/ //throw new java.lang.UnsupportedOperationException("Method isEnd() not yet implemented."); return isEnd; } } }
4. 线程池管理器(ThreadPoolManager):用于创建并管理线程池
import java.util.Vector; /** * <p>Title: </p> * <p>Description: use to test simple thread pool</p> * <p>Copyright: Copyright (c) 2002</p> * <p>Company: </p> * * @author xingyong * * @version 1.0 */ public class ThreadPoolManager { /** * the number of threads in pool */ private int threadNum; /** * the default number of threads in pool */ private int defaultThreadNum; /** * the vector of threads in pool */ private Vector workThreadVector; /** * the vector of tasks */ private Vector taskVector; /** * @param i */ public ThreadPoolManager(int i) { taskVector = new Vector(10, 10); //initial thread number defaultThreadNum = 10; if(i > 0) defaultThreadNum = i; //call thread CreateThreadPool(i); } public ThreadPoolManager() { this(10); } /** * * @return */ public boolean isAllTaskFinish() { return taskVector.isEmpty(); } /** * @return int */ public int getThreadNum() { return threadNum; } /** * create thread pool * @param i */ private void CreateThreadPool(int i) { if(workThreadVector == null) workThreadVector = new Vector(i); Object obj = null; //create threads synchronized(workThreadVector) { for(int j = 0; j < i; j++) { threadNum++; WorkThread workThread = new WorkThread(taskVector, threadNum); workThreadVector.addElement(workThread); } } } /** * add task to task vector and notify work Threads in pool * to do it * @param taskObj */ public void addTask(Task taskObj) { if(taskObj == null) return; synchronized(taskVector) { taskVector.addElement(taskObj); taskVector.notifyAll(); } } /** * destroy threads in pool */ public void closeThread() { Object obj = null; while(!workThreadVector.isEmpty()) { try { WorkThread workThread = (WorkThread)workThreadVector.remove(0); workThread.closeThread(); continue; } catch(Exception exception) { exception.printStackTrace(); } break; } } }
相关推荐
易语言简易线程池的实现。 ——V雪落有声V原创。转载请保留。前文:。为了能充分理解本篇文章的内容,需要了解的知识如下:。1.事件对象的使用:http://baike.baidu.com/view/751499.htm。2.信号量的使用:...
这是一个简单线程池的实现,虽然有很多bug,但是能够简单地实现线程池。
线程池的简单实现,对初学者很有用,希望对大家有所帮助。
该资源为c++11版本的线程池实现,其中调用了c++11相关的新特性,例如thread、function等,推荐新手下载使用!
简易的C++11线程池实现,线程池为固定方式,后面会新增非固定模式。
这是一个很简单的线程池实现 适合刚开始研究线程池的朋友
线程池的简单实现,多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务。线程池线程都是后台线程。每个线程都使用默认的堆栈大小,以默认的优先级运行,并处于多线程单元中。如果某个...
主要介绍了Linux C线程池简单实现实例的相关资料,需要的朋友可以参考下
vs2015 实现的线程池,Task是任务类,Thread线程类。
线程池的实现,简单的实现了线程池的功能,稍微改动就可以应用到项目中了
易语言简易线程池的实现 ——V雪落有声V原创 转载请保留 前文: 为了能充分理解本篇文章的内容,需要了解的知识如下: 1.事件对象的使用:http://baike.baidu.com/view/751499.htm 2.信号量的使用:...
qt 线程池模块实现,可基于此进行后续开发,简单实用。
C语言实现的简单线程池
linux下通过200行C代码实现简单线程池,附源代码和文档说明: 200行C代码实现简单线程池.doc threadpool.c
C线程池简单应用层实现,双向循环链表实现,带参宏链表应用,管道传地址参数实现,地址二级指针赋值。可以用于单线程池实现参考价值。
VC实现的线程池例程,深入地讲解操作系统实现的线程池的优越性,尝试实现一个简单的线程池模型。
简单的线程池,采用.net实现。可以直接在代码中使用
简单线程池的实现。提供添加删除线程,执行任务