请求发出以后,如果没有准备好的一直等待到数据准备好在返回---》谨慎的等待(恶心的名字)
package guarded;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Data {
private BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<String>(1);
public void putRequest(String content){
try {
blockingQueue.put(content);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getRequest(){
try {
return blockingQueue.take();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
}
/*******************************************/
package guarded;
import java.util.Random;
public class ClientThread extends Thread{
private Data data;
public ClientThread(Data data){
this.data =data;
}
public void run(){
for (int i = 0; i < 1000; i++) {
System.out.println("put content:"+i);
data.putRequest(String.valueOf(i));
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/***********************************/
package guarded;
import java.util.Random;
public class ServerThread extends Thread {
private Data data;
public ServerThread(Data data){
this.data =data;
}
public void run(){
while(true){
System.out.println("get content:"+data.getRequest());
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**********************************/
package guarded;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Data data = new Data();
new ServerThread(data).start();
new ClientThread(data).start();
}
}
guarded suspension pattern和productor-comsumer(生产者消费者)很像,这里Data的
blockingQueue的容量是1,productor-comsumer则大于一,productor-comsumer也基本上是多对多关系。
jdk1.4以前主要用wait(),notifyAll()进行控制,现在用
BlockingQueue更加简单
参与者:
Data(存放资源和等待条件等一系列条件和业务处理的类)
ServerThread和ClientThread(处理结果和请求发起的线程)