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.aygfsteel.com/jesson2005/articles/111196.html

          posted on 2008-09-07 11:06 大石頭 閱讀(227) 評論(0)  編輯  收藏 所屬分類: 多線程

          主站蜘蛛池模板: 开江县| 康平县| 庆安县| 武威市| 开江县| 抚远县| 陕西省| 油尖旺区| 进贤县| 万宁市| 祥云县| 会泽县| 永年县| 五原县| 彰武县| 杭锦旗| 怀来县| 玉田县| 元谋县| 卫辉市| 庆安县| 金昌市| 谷城县| 保亭| 镇平县| 徐水县| 青岛市| 安平县| 高安市| 和硕县| 周宁县| 平乐县| 中超| 虎林市| 甘洛县| 施甸县| 宣汉县| 柞水县| 玉门市| 体育| 麦盖提县|