多程线设计模式 -- woker thread pattern
2009-09-17 00:00:00 来源:WEB开发网工作区(核心)
Java代码
public class Channel {
//允许最多请求数
private static final int MAX_REQUEST = 100;
//请求容器
private final Request[] requestQueue;
private int tail; // 下一个putRequest的地方
private int head; // 下一个takeRequest的地方
private int count; // Request的数量
//工作线程组
private final WorkerThread[] threadPool;
public Channel(int threads) {
//初始请求容器
this.requestQueue = new Request[MAX_REQUEST];
this.head = 0;
this.tail = 0;
this.count = 0;
//初始化工作线程组
threadPool = new WorkerThread[threads];
for (int i = 0; i < threadPool.length; i++) {
threadPool[i] = new WorkerThread("Worker-" + i, this);
}
}
//工作线程开始工作
public void startWorkers() {
for (int i = 0; i < threadPool.length; i++) {
threadPool[i].start();
}
}
//添加请求
public synchronized void putRequest(Request request) {
//当容器缓冲请求数大于容器容量时等待
while (count >= requestQueue.length) {
try {
wait();
} catch (InterruptedException e) {
}
}
requestQueue[tail] = request;
//获取下一次放入请求的位置
tail = (tail + 1) % requestQueue.length;
count++;
notifyAll();
}
//处理请求
public synchronized Request takeRequest() {
//当请求数为空时等待
while (count <= 0) {
try {
wait();
} catch (InterruptedException e) {
}
}
Request request = requestQueue[head];
//获取下一次获取请求的位置
head = (head + 1) % requestQueue.length;
count--;
notifyAll();
return request;
}
}
更多精彩
赞助商链接