1 示例

  • ClientTjread.java

package com.gc.language;

public class ClientThread extends Thread{
    private Channel channel;
    public ClientThread(Channel channel) {
            this.channel = channel;
        }
     
    public void run (){
       
        for(int i =0;i<15;i++)
        {
            try{
                Thread.sleep(50);
                }
                catch(InterruptedException e){
                   
                }
            channel.putRequest(new Request());
               
           
        }
       
    }

}
  • Request.java
package com.gc.language;

import java.util.Date;

public class Request {
    // ....
   
    public void execute() {
        // do some work....
       
        System.out .println(new Date());
       
    }
}
  • WorkerThread.java
package com.gc.language;

public class WorkerThread extends Thread {
    private Channel channel;

    public WorkerThread(Channel channel) {
        this.channel = channel;
    }

    // ...

    public void run() {
        while(true) {
            try{
            Thread.sleep(5000);
            }
            catch(InterruptedException e){
               
            }
            Request request = channel.getRequest();
            request.execute();
          
        }
    }
}
  • Channel.java
package com.gc.language;

import java.util.LinkedList;

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

    public Channel(int threadNumber) {
        requests = new LinkedList();
        ClientThread cthread = new ClientThread (this);
        cthread.start();
        workerThreads = new WorkerThread[threadNumber];
        for(int i = 0; i < workerThreads.length; i++) {
            workerThreads[i] = new WorkerThread(this);
            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 getRequest() {
        while(requests.size() <= 0) {
            try {
                wait();
            }
            catch(InterruptedException e) {}
        }

        Request request = (Request) requests.removeFirst();
        notifyAll();
     
        return request;
    }
}
  • Test.java
package com.gc.language;


public class Test {
    public static void main(String[] args){
       
        Channel channel = new Channel(10);
    }


}
2 观念
Worker Thread模式在Request的管理上像P-C模式,在Request的行为上像Command模式。P-C模式关注Product(Request)如何生产消费,Worker Thread模式关注产品被消费时 做何处理