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 大石頭 閱讀(226) 評論(0)  編輯  收藏 所屬分類: 多線程

          主站蜘蛛池模板: 白水县| 青海省| 肥城市| 清苑县| 如皋市| 中卫市| 新乡县| 疏附县| 辉南县| 桑植县| 壤塘县| 江源县| 周宁县| 防城港市| 本溪| 哈尔滨市| 新昌县| 宾阳县| 赤城县| 庆云县| 徐闻县| 余干县| 台安县| 庆阳市| 民权县| 霍林郭勒市| 长沙县| 元朗区| 招远市| 彝良县| 朔州市| 永州市| 安顺市| 慈利县| 崇左市| 馆陶县| 舞钢市| 栾川县| 韶山市| 上犹县| 孟津县|