首页 > 代码库 > java并发编程之Guarded Suspention

java并发编程之Guarded Suspention

当客户端请求速度远远大于服务端的处理速度,这时候就非常适合使用Guarded Suspention模式

package cn.fcl.guardendSuspension;
import java.util.ArrayList;
import java.util.List;
public class RequestQueue {
private List<Integer> integers = new ArrayList<Integer>();
public synchronized Integer get() {
if(integers.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
}
}
return integers.remove(0);
}
public synchronized void add(Integer i) {
integers.add(i);
notify();
}
}
package cn.fcl.guardendSuspension;
public class Client extends Thread {
private RequestQueue queue;
public Client(RequestQueue queue) {
super();
this.queue = queue;
}
public void run() {
for(int i = 0; i < 10; i++) {
queue.add(i);
}
System.out.println("请求完毕");
}
}
package cn.fcl.guardendSuspension;
public class Server extends Thread{
private RequestQueue queue;
public Server(RequestQueue queue) {
this.queue = queue;
}
@Override
public void run() {
while(true) {
Integer i = queue.get();
System.out.println(i + "已经处理");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package cn.fcl.guardendSuspension;
public class main {
public static void main(String[] args) {
RequestQueue queue = new RequestQueue();
new Client(queue).start();
new Server(queue).start();
}
}
 

 

本文出自 “温故而知新” 博客,请务必保留此出处http://fangchunliu.blog.51cto.com/1269779/1411302