Worker Thread模式在Request的管理上像是 Producer Consumer 模式,在Request的行为上像是 Command 模式。
Producer Consumer模式专注于Product的生产与消费,至于Product被消费时是作何处理,则不在它的讨论范围之中。
如果您的Product是一个Request,消费者取得Request之后,执行Request中指定的请求方法,也就是使用Command模式,并且您的Request缓冲区还管理了Consumer,就有Worker Thread模式的意思了。
在Sequence Diagram上,可以看出Worker Thread同时展现了Producer Consumer模式与Command模式:
利用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()中。
Producer Consumer模式专注于Product的生产与消费,至于Product被消费时是作何处理,则不在它的讨论范围之中。
如果您的Product是一个Request,消费者取得Request之后,执行Request中指定的请求方法,也就是使用Command模式,并且您的Request缓冲区还管理了Consumer,就有Worker Thread模式的意思了。
在Sequence Diagram上,可以看出Worker Thread同时展现了Producer Consumer模式与Command模式:
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()中。