(^^)/JavaマルチスレッドGuarded-SUspensionモード


第1種
 
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.サーバー側
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();
		}
	}
}

 
 
 
 
 
 
 
 
 
 
 
第2種
戻り値があります...