본문 바로가기

Development/Programming

[Java Design Patten] Guarded Suspension

이 처리를 실행하면 안 될 때 처리하기 직전에 쓰레드를 기다리게 하는 패턴이다.


아래의 시퀀스 다이어그램을 참고~!




public class Request {

private final String name;

public Request (final String name) {

this.name = name;

}

public String getName () {

return this.name;

}


public String toString() {

return "Request [name=" + name + "]";

}

}



 public class RequestQueue {


private final Queue<Request> queue = new LinkedList<Request>();

public synchronized Request getRequest () {

while (queue.peek() == null) {

try {

wait();

} catch (final InterruptedException e) {

}

}

return queue.remove();

}

public synchronized void putRequest (final Request request) {

queue.offer(request);

notifyAll();

}

}


 public class ClientThread extends Thread {

private final Random random;

private final RequestQueue requestQueue;

public ClientThread (final RequestQueue requestQueue, final String name, final Long seed) {

super(name);

this.requestQueue = requestQueue;

this.random = new Random(seed);

}

public void run () {

for (int i=0;i<10000;i++) {

final Request request = new Request("NO." + i);

System.out.println(Thread.currentThread().getName() + "requests " + request);

requestQueue.putRequest(request);

try {

Thread.sleep(random.nextInt(1000));

} catch (final InterruptedException e){

}

}

}

}


 public class ServerThread extends Thread {

private final Random random;

private final RequestQueue reqeustQueue;

public ServerThread (final RequestQueue reqeustQueue, final String name, final Long seed) {

super(name);

this.reqeustQueue = reqeustQueue;

this.random = new Random(seed);

}

public void run () {

for (int i=0;i<10000;i++) {

final Request reqeust = reqeustQueue.getRequest();

System.out.println(Thread.currentThread().getName() + " handles " + reqeust);

try {

Thread.sleep(random.nextInt(1000));

} catch (final InterruptedException e) {

}

}

}

}



public class Main {

public static void main (final String[] args) {

final RequestQueue requestQueue = new RequestQueue();

new ClientThread (requestQueue, "A", 111111L).start();

new ServerThread (requestQueue, "A", 523141L).start();

}

}