今天看了下线程池,觉得挺有意思,自己写了一个,不知道有没有理解错,希望大家指点下,给点宝贵意见建议~
public interface Job {
public void run();
}
import java.util.Stack;/**
- 线程池
-
@author xmj
*
*/
public class ThreadPool{
private int maxThread; //最大线程数
private int currThreadCount; //当前线程数
private Stack waitstack; //空闲线程栈/**
- @param max 线程池最大线程数
- @param job 线程工作类 */ public ThreadPool(int max) { this.maxThread=max; this.currThreadCount=0; this.waitstack=new Stack(); MyThread[] threads=new MyThread[max]; for(int i=0;i<max;i++) { threads[i]=new MyThread(i); waitstack.add(threads[i]); threads[i].start(); } }
/**
- @author xmj
-
内部线程类
*
*/
private class MyThread extends Thread
{
private int id; //线程ID
private Job job; //任务
private boolean stop=false; //停止标志public MyThread(int id)
{
this.id=id;
}
/**- @param job 任务 */ public void setJob(Job job) { this.job=job; }
/**
- 停止线程 * */ public void threadstop() { stop=true; }
public void run()
{
while(!stop)
{
if(job==null)
{
//没任务就进入等待
synchronized(this){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
job.run();//运行作业/** * 如果该线程不是扩展线程,则清空任务,继续等待,并入栈 * 否则结束 */ if(this.id<=maxThread) { job=null; } } } currThreadCount--;
}
}
/**
- 添加新线程任务
- @param job 任务 */ public void addJob(Job job) { currThreadCount++; if(waitstack.isEmpty()) { MyThread exThread=new MyThread(currThreadCount); exThread.start(); } else { MyThread t=(MyThread)waitstack.pop(); t.setJob(job); synchronized(t){ t.notify(); } } }
/**
- 回收线程
- @param t 完成任务的线程
- */ public void push(MyThread t) { waitstack.push(t); currThreadCount--; }
/**
- 清理工作 * */ public void kill() { while(currThreadCount!=0) { while(!waitstack.isEmpty()) { MyThread t=(MyThread)waitstack.pop(); t.threadstop(); t.notify(); currThreadCount--; } waitstack=null; } }
}
问题补充
各位老大,给点意见啊~~~