线程池的设计问题
我想问的是怎么让线程可以复用? 实现的时候需要怎么处理?
参考以下的实现方式。
class Pool
{
Runner r;
public void execute(Runnable task)
{
r.setTask(task);
r.notifyAll();
}
}
class Runner implements Runnable
{
protected Runnable task;
public void setTask(Runnable task)
{
this.task = task;
}
public void run()
{
while(true)
{
try
{
if(this.task != null)
{
task.run();
this.task = null;
}
else
{
synchronized(this)
{
this.wait()
}
}
}
catch(Exception e)
{}
}
}
}
如果你能够明白一点点了,用2-3天的时间安静的思考一下,也可以做一个原型尝试运行一下,然后再带着问题来看看这个帖子,相信你可以获得一些收获的。
通过setTask(task)这里唤醒Runner里面的run()方法,从而不断得去检测是否有新任务,有就执行它本身多实现的run(),没有就继续等待。。感觉是在用notifyAll()和wait()来实现调度。。这样理解靠谱不?
这些还是表面现象,还差一步就接触到核心了。加油呀!