keep moving!

We must not cease from exploration. And the end of all our exploring will be to arrive where we began and to know the place for the first time.
随笔 - 37, 文章 - 2, 评论 - 3, 引用 - 0
数据加载中……

Design Pattern: Worker Thread 模式

Worker Thread模式在Request的管理上像是 Producer Consumer 模式,在Request的行為上像是 Command 模式

Producer Consumer模式專注於Product的生產與消費,至於Product被消費時是作何處理,則不在它的討論範圍之中。
WorkerThread

如果您的Product是一個Request,消費者取得Request之後,執行Request中指定的請求方法,也就是使用Command模式,並且您的Request緩衝區還管理了Consumer,就有Worker Thread模式的意思了。
WorkerThread

在Sequence Diagram上,可以看出Worker Thread同時展現了Producer Consumer模式與Command模式:
WorkThread
利用Java實現的一個Channel類如下所示:
  • Channel.java
import java.util.LinkedList; 

public class Channel {
private LinkedList requests;
private WorkerThread[] workerThreads;

public Channel(int threadNumber) {
requests = new LinkedList();
workerThreads = new WorkerThread[threadNumber];
for(int i = 0; i < workerThreads.size(); i++) {
workerThreads[i] = new WorkerThread();
workerThreads[i].start();
}
}

public synchronized void putRequest(Request request) {
while(requests.size() >= 2) { // 容量限制為 2
try {
wait();
}
catch(InterruptedException e) {}
}

requests.addLast(request);
notifyAll();
}

public synchronized Request getProduct() {
while(requests.size() <= 0) {
try {
wait();
}
catch(InterruptedException e) {}
}

Request request = (Request) requests.removeFirst();
notifyAll();

return request;
}
}

Request類與WorkerThread類之間採的Command模式:
  • Request.java
public class Request() { 
// ....

public void execute() {
// do some work....
}
}

  • WorkerThread.java
public class WorkerThread extends Thread { 
// ...

public void run() {
while(true) {
Request request = channel.getRequest();
request.execute();
}
}
}

就行為上,WorkerThread就是有請求來了就作,如果沒有請求,則所有的WorkerThread就等待,直到有新的工作進來而通知它們,取得請求的WorkerThread要作的工作,就直接定義在execute()中。



张金鹏 2007-04-17 10:56 发表评论

文章来源:http://www.blogjava.net/jesson2005/articles/111196.html

posted on 2008-09-07 11:06 大石头 阅读(218) 评论(0)  编辑  收藏 所属分类: 多线程


只有注册用户登录后才能发表评论。


网站导航: