ClientThread:表示发送请求的线程
public class ClientThread extends Thread{
private final Random random;
private final RequestQueue requestQueue;
public ClientThread(RequestQueue requestQueue,String name,long seed){
super(name);
this.random = new Random(seed);
this.requestQueue = requestQueue;
}
public void run(){
for (int i = 0;i < 10000;i++){
Request request = new Request("No. " + i);
System.out.println(Thread.currentThread().getName() + " request " + request);
requestQueue.putRequest(request);
try {
Thread.sleep(random.nextInt(1000));
}catch (InterruptedException e){
}
}
}
}
Main
public class Main {
public static void main(String[] args) {
RequestQueue requestQueue = new RequestQueue();
new ClientThread(requestQueue,"alex",3141592L).start();
new ServerThread(requestQueue,"bobby",6535897L).start();
}
}
Request
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:依次存放请求的类
public class RequestQueue {
private final Queue<Request> queue = new LinkedList<Request>();
public synchronized Request getRequest() {
while (queue.peek() == null){
try {
wait();
}catch (InterruptedException e){
}
}
return queue.remove();
}
public synchronized void putRequest(Request request){
queue.offer(request);
notifyAll();
}
}
ServerThread:表示接收请求的类
public class ServerThread extends Thread{
private final Random random;
private final 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() + " handles " + request);
try {
Thread.sleep(random.nextInt(1000));
}catch (InterruptedException e){
}
}
}
}