[url=http://www.iteye.com/topic/104432]LZ[/url]的思路,是线程共享任务队列,线程按同步方法获取一个非空的任务执行:工作线程自己去“拉单”干。
我提供另外一种思路,线程是被动,由别人(监工)分配,激发:
有一个主线程--“监工”:负责查看任务队列中是否有任务,如果有,取出一个任务,设置到一个“空闲”的线程中,并notify该线程。
[code]
while (hasTask) {
1、get the task from task quene
2、get an waiting worker thread, or create a new workder thread
3、set the task to the thread, and set the thread status running
synchronized(thread) {
4、thread.nofity();//not notifyAll()
}
}
[/code]
线程类的run方法会是这样的:
[code]
synchronized(this) {
while (!shutdown) {
if (status == running) {
1、run the task;
2、task = null;
3、status = waiting;
4、manager.done(this, task);//告知监工自己已经完成这个任务
}
5、this.wait();
}
}
[/code]
我提供另外一种思路,线程是被动,由别人(监工)分配,激发:
有一个主线程--“监工”:负责查看任务队列中是否有任务,如果有,取出一个任务,设置到一个“空闲”的线程中,并notify该线程。
[code]
while (hasTask) {
1、get the task from task quene
2、get an waiting worker thread, or create a new workder thread
3、set the task to the thread, and set the thread status running
synchronized(thread) {
4、thread.nofity();//not notifyAll()
}
}
[/code]
线程类的run方法会是这样的:
[code]
synchronized(this) {
while (!shutdown) {
if (status == running) {
1、run the task;
2、task = null;
3、status = waiting;
4、manager.done(this, task);//告知监工自己已经完成这个任务
}
5、this.wait();
}
}
[/code]