一个简单的线程池实现(java版)

线程池代码:

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->
importjava.util.List;
importjava.util.Vector;

public class ThreadPool
ExpandedBlockStart.gifContractedBlock.gif
{
privatestaticThreadPoolinstance_=null;
//定义优先级别常数,空闲的线程按照优先级不同分别存放在三个vector中
publicstaticfinalintLOW_PRIORITY=0;
publicstaticfinalintNORMAL_PRIORITY=1;
publicstaticfinalintHIGH_PRIORITY=2;
//保存空闲线程的List,或者说它是"池"
privateList<PooledThread>[]idleThreads_;
privatebooleanshutDown_=false;
privateintthreadCreationCounter_;//以创建的线程的个数
privatebooleandebug_=false;//是否输出调试信息
//构造函数,因为这个类视作为singleton实现的,因此构造函数为私有
privateThreadPool()
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
//产生空闲线程.三个vector分别存放分别处在三个优先级的线程的引用
ExpandedSubBlockStart.gifContractedSubBlock.gif
List[]idleThreads={newVector(5),newVector(5),newVector(5)};
idleThreads_
=idleThreads;
threadCreationCounter_
=0;
}


ExpandedSubBlockStart.gifContractedSubBlock.gif
publicintgetCreatedThreadsCount(){
returnthreadCreationCounter_;
}

//通过这个函数得到线程池类的实例
ExpandedSubBlockStart.gifContractedSubBlock.gif
publicstaticThreadPoolinstance(){
if(instance_==null)
instance_
=newThreadPool();
returninstance_;
}


ExpandedSubBlockStart.gifContractedSubBlock.gif
publicbooleanisDebug(){
returndebug_;
}


//将线程repoolingThread从新放回到池中,这个方式是同步方法。
//这个方法会在多线程的环境中调用,设计这个方法的目的是让工作者线程
//在执行完target中的任务后,调用池类的repool()方法,
//将线程自身从新放回到池中。只所以这么做是因为线程池并不能预见到
//工作者线程何时会完成任务。参考PooledThread的相关代码。
protectedsynchronizedvoidrepool(PooledThreadrepoolingThread)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
if(!shutDown_)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
if(debug_)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
System.
out.println("ThreadPool.repool():repooling");
}

switch(repoolingThread.getPriority())
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
caseThread.MIN_PRIORITY:
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
idleThreads_[LOW_PRIORITY].add(repoolingThread);
break;
}

caseThread.NORM_PRIORITY:
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
idleThreads_[NORMAL_PRIORITY].add(repoolingThread);
break;
}

caseThread.MAX_PRIORITY:
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
idleThreads_[HIGH_PRIORITY].add(repoolingThread);
break;
}

default:
thrownewIllegalStateException("IllegalpriorityfoundwhilerepoolingaThread!");
}

notifyAll();
//通知所有的线程
}

else
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
if(debug_)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
System.
out.println("ThreadPool.repool():Destroyingincomingthread.");
}

repoolingThread.shutDown();
//关闭线程
}

if(debug_)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
System.
out.println("ThreadPool.recycle():done.");
}

}


publicvoidsetDebug(booleannewDebug)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
debug_
=newDebug;
}


//停止池中所有线程
publicsynchronizedvoidshutdown()
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
shutDown_
=true;
if(debug_)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
System.
out.println("ThreadPool:shuttingdown");
}

for(intprioIndex=0;prioIndex<=HIGH_PRIORITY;prioIndex++)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
ListprioThreads
=idleThreads_[prioIndex];
for(intthreadIndex=0;threadIndex<prioThreads.size();threadIndex++)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
PooledThreadidleThread
=(PooledThread)prioThreads.get(threadIndex);
idleThread.shutDown();
}

}

notifyAll();
if(debug_)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
System.
out.println("ThreadPool:shutdowndone.");
}

}


//以Runnable为target,从池中选择一个优先级为priority的线程创建线程
//并让线程运行。
publicsynchronizedvoidstart(Runnabletarget,intpriority)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
PooledThreadthread
=null;//被选出来执行target的线程
ListidleList=idleThreads_[priority];
if(idleList.size()>0)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
//如果池中相应优先级的线程有空闲的,那么从中取出一个
//设置它的target,并唤醒它
//从空闲的线程队列中获取
intlastIndex=idleList.size()-1;
thread
=(PooledThread)idleList.get(lastIndex);
idleList.remove(lastIndex);
thread.setTarget(target);
}

//池中没有相应优先级的线程
else
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
threadCreationCounter_
++;
//创建新线程,
thread=newPooledThread(target,"PooledThread#"+threadCreationCounter_,this);
//新线程放入池中
switch(priority)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
caseLOW_PRIORITY:
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
thread.setPriority(Thread.MIN_PRIORITY);
break;
}

caseNORMAL_PRIORITY:
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
thread.setPriority(Thread.NORM_PRIORITY);
break;
}

caseHIGH_PRIORITY:
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
thread.setPriority(Thread.MAX_PRIORITY);
break;
}

default:
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
thread.setPriority(Thread.NORM_PRIORITY);
break;
}

}

//启动这个线程
thread.start();
}

}

}

工作者线程代码:

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--> public class PooledThreadextendsThread
ExpandedBlockStart.gifContractedBlock.gif
{
privateThreadPoolpool_;//池中线程需要知道自己所在的池
privateRunnabletarget_;//线程的任务
privatebooleanshutDown_=false;
privatebooleanidle_=false;//设置是否让线程处于等待状态

ExpandedSubBlockStart.gifContractedSubBlock.gif
privatePooledThread(){
super();
}


privatePooledThread(Runnabletarget)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
super(target);
//初始化父类
}


privatePooledThread(Runnabletarget,Stringname)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
super(target,name);
}


publicPooledThread(Runnabletarget,Stringname,ThreadPoolpool)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
super(name);
pool_
=pool;
target_
=target;
}


privatePooledThread(Stringname)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
super(name);
//初始化父类
}


privatePooledThread(ThreadGroupgroup,Runnabletarget)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
super(group,target);
}


privatePooledThread(ThreadGroupgroup,Runnabletarget,Stringname)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
super(group,target,name);
}


privatePooledThread(ThreadGroupgroup,Stringname)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
super(group,name);
}


publicjava.lang.RunnablegetTarget()
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
returntarget_;
}


publicbooleanisIdle()
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
returnidle_;//返回当前的状态
}


//工作者线程与通常线程不同之处在于run()方法的不同。通常的线程,
//完成线程应该执行的代码后,自然退出,线程结束。
//虚拟机在线程结束后收回分配给线程的资源,线程对象被垃圾回收。]
//而这在池化的工作者线程中是应该避免的,否则线程池就失去了意义。
//作为可以被放入池中并重新利用的工作者线程,它的run()方法不应该结束,
//随意,在随后可以看到的实现中,run()方法执行完target对象的代码后,
//就将自身repool(),然后调用wait()方法,使自己睡眠而不是退出循环和run()。
//这就使线程池实现的要点。
publicvoidrun()
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
//这个循环不能结束,除非池类要求线程结束
//每一次循环都会执行一次池类分配给的任务target
while(!shutDown_)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
idle_
=false;
if(target_!=null)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
target_.run();
//运行target中的代码
}

idle_
=true;
try
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
//线程通知池重新将自己放回到池中
pool_.repool(this);//
//进入池中后睡眠,等待被唤醒执行新的任务,
//这里是线程池中线程于普通线程的run()不同的地方。
synchronized(this)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
wait();
}

}

catch(InterruptedExceptionie)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
}

idle_
=false;
}

//循环这里不能结束,否则线程结束,资源被VM收回,
//就无法起到线程池的作用了
}



publicsynchronizedvoidsetTarget(java.lang.RunnablenewTarget)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{//设置新的target,并唤醒睡眠中的线程
target_=newTarget;//新任务
notifyAll();//唤醒睡眠的线程
}


publicsynchronizedvoidshutDown()
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
shutDown_
=true;
notifyAll();
}

}


测试代码:

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--> public static void main(String[]args)
ExpandedBlockStart.gifContractedBlock.gif
{
System.
out.println("TestingThreadPool");
System.
out.println("CreatingThreadPool");
ThreadPoolpool
=ThreadPool.instance();
pool.setDebug(
true);
classTestRunnerimplementsRunnable
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
publicintcount=0;
publicvoidrun()
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
System.
out.println("Testrunnersleeping5seconds");
//此方法使本线程睡眠5秒
synchronized(this)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
try
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
wait(
5000);//等待5秒时间
}

catch(InterruptedExceptionioe)
ExpandedSubBlockStart.gifContractedSubBlock.gif
{
}

}

System.
out.println("Testrunnerleaving");
count
++;
}

}

System.
out.println("Startinganewthread");
TestRunnerrunner
=newTestRunner();
pool.start(runner,pool.HIGH_PRIORITY);
System.
out.println("count:"+runner.count);
System.
out.println("Threadcount:"+pool.getCreatedThreadsCount());
pool.shutdown();
}

}

测试结果:

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--> TestingThreadPool
CreatingThreadPool

Startinganewthread

Testrunnersleeping
5 seconds
count:
0
Threadcount:
1
ThreadPool:shuttingdown

ThreadPool:shutdowndone
.
Testrunnerleaving

ThreadPool
. repool () :Destroyingincomingthread .
ThreadPool
. recycle () :done .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值