让我们来共同实现一个线程池(一)

时间:2008-01-16 12:57:56  来源:  作者:

最近看了一本好书,想按照书中的例子实现一个实用的线程池,正在进行中...,今天才写代码,希望各位高手,老手,新手能够帮忙一起实现,要的就是这个分析的过程.希望大家鼎立支持.先贴出全部代码.

线程池和工作线程类:(这里的代码和书中的没有什么改动,不会侵权吧? :oops: )

package threadstudy;

import java.util.LinkedList;

public class ThreadPool{
//the number of thread
private final int sThread;

//the collection of thread
private final WorkThread[] threads;

//the queue of task
private final LinkedList queue;

//Creator
public ThreadPool(int sThread){
this.sThread = sThread;
queue = new LinkedList();
threads = new WorkThread[this.sThread];
for(int i=0; i<sThread; i++){
threads = new WorkThread();
threads.start();// start all thread
}
}
public void execute(Runnable task){
synchronized(this.queue){
queue.addLast(task);
queue.notify();
}
}

/**
 * the worker of threadpool is inner class
 */
private class WorkThread extends Thread{
Runnable task = null;
public void run(){
try{
while(true){
synchronized(queue){ //avoid race condition occur between isEmpty and romoveFirst
while(queue.isEmpty()){
queue.wait();
}
task = (Runnable)queue.removeFirst();
}
task.run(); //run the task
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}



抽象任务类:


package threadstudy;

public abstract class AbstractTask implements Runnable{
private String _taskname = null;

public String getTaskname(){
return this._taskname;
}

public void setTaskname(String taskname){
this._taskname = taskname;
}

public void run(){

}

public String toString(){
return "this task's attribute : taskname = " + _taskname + "!";
}
}


一个简单的任务类:

package threadstudy;

public class SimpleTask extends AbstractTask{
public void run(){//runnable
try{
  //Thread.sleep(100);
}
catch(Exception ex){
}

System.out.println(this.toString());
}
}


测试客户端:

package threadstudy;

public class MainClient{
public static final int POOL_SIZE = 5;
public static void main(String[] args){
//build TreadPool
ThreadPool pool = new ThreadPool(POOL_SIZE);
for(int i=0;i< 100;i++){
AbstractTask task = new SimpleTask();
task.setTaskname("task" + i);
pool.execute(task);
}
}
}


如果谁有好的线程池的例子,和好的想法,还有对以上程序改进的意见请拿出来给大家分享,今天就到这里,我要回家了,过会就没有公车了.



 镖师甲 回复于:2004-09-30 20:28:44

十一国庆节后继续,哈哈




原文链接:http://bbs.chinaunix.net/viewthread.php?tid=416780
转载请注明作者名及原文出处


文章评论

共有 位网友发表了评论 查看完整内容