---
title: "Guarded Suspension Pattern"
author: "liangxianfu5811"
date: "2012-06-30T17:55:34Z"
tags: []
categories: ["编程语言"]
slug: "guarded-suspension-pattern"
draft: false
lastmod: "2012-06-30T17:59:15Z"
id: 1572143
url: "https://love5811.iteye.com/blog/1572143"
---

防卫暂停模式
Guarded Suspension Pattern的参与者：(对应Java设计模式中的"生产消费者模式")
GuardedObject(被防卫的对象)参与者，GuardedObject参与者是一个拥有被防卫的方法(guardedMethod)的类，当线程执行guardedMethod时，只要满足警戒条件，就会马上执行，但警戒条件不成立时，就要开始等待，警戒条件的成立与否，会随GuardedObject参与者的状态改变而变化；GuardedObject参与者除了guardedMethod以外，可能还会有用来更改实例状态(特别是用来更改警戒条件)的方法(stateChangingMethod)；Java语言中，使用while语句与wait方法来实现guardedMethod的，而是用notify/notifyAll方法来实现stateChangingMethod，在以下范例程序中，RequestQueue类就是GuardedObject参与者，getRequest方法与putRequest方法则分别是guardedMethod与stateChangingMethod
========Request类
public class Request {

	private final String name;

	public Request(String name) {
		this.name = name;
	}

	public final String getName() {
		return name;
	}

	public String toString() {
		return "";
	}
}

=======RequestQueue类
public class RequestQueue {

	private final LinkedList<Request> queue = new LinkedList();

	public synchronized Request getRequest() {
		try {
			while (0 >= queue.size()) {
				this.wait();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return (Request) queue.removeFirst();
	}

	public synchronized void putRequest(Request request) {
		queue.addLast(request);
		notifyAll();
	}
}
=======ClientRequest类
public class ClientRequest extends Thread {

	private Random random;
	private RequestQueue queue;

	public ClientRequest(RequestQueue queue, String name, long seed) {
		super(name);
		this.random = new Random(seed);
		this.queue = queue;
	}

	public void run() {
		try {
			Request request = null;
			for (int i = 0; i < 10000; i++) {
				request = new Request("No." + i);
				System.out.println(Thread.currentThread().getName()
						+ " requests " + request);
				queue.putRequest(request);
				Thread.sleep(this.random.nextInt(1000));
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
=======ServerReqiest类
public class ServerRequest extends Thread {

	private Random random;
	private RequestQueue queue;

	public ServerRequest(RequestQueue queue, String name, long seed) {
		super(name);
		this.queue = queue;
		this.random = new Random(seed);
	}

	public void run() {
		try {
			Request request = null;
			for (int i = 0; i < 10000; i++) {
				request = queue.getRequest();
				System.out.println(Thread.currentThread().getName()
						+ " handles " + request);
				Thread.sleep(this.random.nextInt(1000));
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
=========测试类
public class Main {

	public static void main(String args) {
		RequestQueue queue = new RequestQueue();
		new ClientRequest(queue, "Alice", 3141592L).start();
		new ServerRequest(queue, "Bobby", 6535897L).start();
	}
}