\(^_^)/ Java多线程Guarded-Suspension模式

第一种

 

1.请求

package guarded_suspension;

public class Request {
	// 模拟请求内容
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Request(String name) {
		this.name = name;
	}

}

 

2.请求队列

package guarded_suspension;

import java.util.LinkedList;

public class RequestQueue {
	private LinkedList queue = new LinkedList();

	public synchronized Request getRequest() {
		while (queue.size() == 0) {
			try {
				wait(); // 等待,直到有新的request加入
			} catch (InterruptedException ex) {

			}
		}
		// 返回request队列中的第一个请求
		return (Request) queue.remove();
	}

	public synchronized void addRequest(Request request) {
		// 加入新的request请求
		queue.add(request);
		// 通知getRequest方法
		notifyAll();
	}
}

 

3.Server端

package guarded_suspension;

public class ServerThread extends Thread {
	// 请求队列
	private RequestQueue requestQueue;

	public ServerThread(RequestQueue requestQueue, String name) {
		super(name);
		this.requestQueue = requestQueue;
	}

	public void run() {
		while (true) {
			// 得到请求
			final Request request = requestQueue.getRequest();
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + " handle " + request);
		}
	}
}

 

4.Client端

package guarded_suspension;

public class ClientThread extends Thread {
	// 请求队列
	private RequestQueue requetQueue;

	public ClientThread(RequestQueue requestQueue, String name) {
		super(name);
		this.requetQueue = requestQueue;
	}

	public void run() {
		for (int i = 0; i < 10; i++) {
			Request request = new Request("RequestId " + i + " Thread Name " + Thread.currentThread().getName());
			System.out.println(Thread.currentThread().getName() + " requests " + request);
			requetQueue.addRequest(request);
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("Client Thread Name is " + Thread.currentThread().getName());
		}
		System.out.println(Thread.currentThread().getName() + " request end.");
	}
}

 

5.测试类

package guarded_suspension;

public class Test {
	public static void main(String[] args) {
		RequestQueue requestQueue = new RequestQueue();
		for (int i = 0; i < 10; i++) {
			new ServerThread(requestQueue, "ServerThread-" + i).start();
		}
		for (int i = 0; i < 10; i++) {
			new ClientThread(requestQueue, "ClientThread-" + i).start();
		}
	}
}

 

 

 

 

 

 

 

 

 

 

 

第二种

有返回值... ...

你可能感兴趣的:(java多线程)