Guarded Suspension Pattern

       Guraded Suspend Partten是当前不适合执行时,就进行等待,直到被唤醒去执行。

 

        类Request用来表示请求,这里没有特殊的处理。

        RequestQueue是一个队列,用来存储所有由ClientThread发出来的请求,它有两个synchronized方法getRequest和putRequest,putRequest是向队列中存储一个请求,而getRequest是从队列中取出一个请求,如果队列为空,那么就进行等待。

 

public class Request {
	private String name;
	public Request(String name){
		this.name=name;
	}
	public String getName(){return name;}
	public String toString(){
		return "[Request "+name+"]";
	}
}

 

import java.util.LinkedList;

public class RequestQueue {
	private final LinkedList<Request> queue=new LinkedList<Request>();
	public synchronized Request getRequest(){
		while(queue.size()<=0)
			try{
				wait(); //不能sleep(100),因为它会一直占线程,synchronized,其他线程没有机会
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		return (Request)queue.removeFirst();
	}
	
	public synchronized void putRequest(Request request){
		queue.addLast(request);
		notifyAll();
	}
}

 

 

        类ClientThread用来表示请求的线程,它不断的请求Request”No.0“、"No.1"、"No.2"。。。,并且将请求的Request放到队列中。

        类ServerThread是处理请求,它从队列中不断的读取线程。

 

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);
	}
	@Override
	public void run(){
		for(int i=0;i<10000;i++){
			Request request=new Request("N0."+i);
			System.out.println(Thread.currentThread().getName()+" requests "+request);
			requestQueue.putRequest(request);
			try{
				Thread.sleep(random.nextInt(1000));
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
	}

}

 

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);
	}
	@Override
	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){
				e.printStackTrace();
			}
		}
	}

}

 运行结果:

Ally requests [Request N0.0]
Bob handles [Request N0.0]
Ally requests [Request N0.1]
Ally requests [Request N0.2]
Bob handles [Request N0.1]
Bob handles [Request N0.2]
Ally requests [Request N0.3]
Bob handles [Request N0.3]
Ally requests [Request N0.4]
Bob handles [Request N0.4]
Ally requests [Request N0.5]

 

        这里有一个等待,也就是while("警戒条件"的否定){ 使用wait等待 },他会一直到条件满足后,这个进程才会继续。

        队列中用了两个synchronized方法,它是用来保护RequestQueue的字段,例如判断size是否大于0、从queue中取出一个元素。

        这种模式有三个特征:有循环体的存在、有条件的测试、因为某种原因在等待。

 

 

你可能感兴趣的:(等待,测试条件)