在家换衣服时,突然门铃响了,原来邮递员送快递了。因为衣服不能换了一半就出去,所以对邮递员将,请您稍等。在把门打开,说“让您久等了”,Guarded Suspension Pattern 就是适合这种情况的
下面我们用个简单的例子来进行说明(范例由5个文件组成): 大家在要注意为什么要加synchronized ,它想保护的究竟是什么,为什么要wait,为什么put后要nitifyAll();
Main.java--调用类
public class Main {
public static void main(String[] args) {
RequestQueue requestQueue = new RequestQueue();
new ClientThread(requestQueue, "邮递员", 3141592L).start();
new ServerThread(requestQueue, "主人", 6535897L).start();
}
}
Request.java--请求类
public class Request {
private final String name;
public Request(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String toString() {
return "[ Request " + name + " ]";
}
}
RequestQueue.java--请求队列
import java.util.LinkedList;
public class RequestQueue {
private final LinkedList queue = new LinkedList();
public synchronized Request getRequest() {
while (queue.size() <= 0) {
try {
wait();
} catch (InterruptedException e) {
}
}
return (Request)queue.removeFirst();
}
public synchronized void putRequest(Request request) {
queue.addLast(request);
notifyAll();
}
}
ClientThread.java--送出请求类
import java.util.Random;
public class ClientThread extends Thread {
private Random random;
private RequestQueue requestQueue;
public ClientThread(RequestQueue requestQueue, String name, long seed) {
super(name);
this.requestQueue = requestQueue;
this.random = new Random(seed);
}
public void run() {
for (int i = 0; i < 10000; i++) {
Request request = new Request("No." + i);
System.out.println(Thread.currentThread().getName() + " 送出请求 " + request);
requestQueue.putRequest(request);
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
}
}
}
}
ServerThread.java--接受请求类
import java.util.Random;
public class ServerThread extends Thread {
private Random random;
private RequestQueue requestQueue;
public ServerThread(RequestQueue requestQueue, String name, long seed) {
super(name);
this.requestQueue = requestQueue;
this.random = new Random(seed);
}
public void run() {
for (int i = 0; i < 10000; i++) {
Request request = requestQueue.getRequest();
System.out.println(Thread.currentThread().getName() + " 处理 " + request);
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
}
}
}
}