본문 바로가기

Development/Programming

[Java Design Patten] Single Threaded Execution

Gate 클래스는 SharedResource 역할을 담당하고 있다. 그리고 자세히 보면 pass 에 Synchronized 키워드를 사용한 것을 주목하자 

사용한 이유는 동시에 복수의 Thread가 접근하면 문제가 발생하기 때문이다.


public class Gate {

private int counter = 0;

private String name = "Nobody";

private String address = "NoWhere";

public synchronized void pass (final String name, final String address) {

this.counter++;

this.name = name;

this.address = address;

check();

}

public String toString () {

return "No." + counter + ": " + name + ", " + address;

}

private void check () {

if (name.charAt(0) != address.charAt(0)) {

System.out.println("BROKEN");

}

}

}


public class UserThread extends Thread {

private final Gate gate;

private final String myname;

private final String myAddress;

public UserThread (final Gate gate, final String myname, final String myAddress) {

this.gate = gate;

this.myname = myname;

this.myAddress = myAddress;

}

public void run () {

System.out.println(myname + "BEGIN");

while (true) {

gate.pass(myname, myAddress);

}

}

}


public class Main {

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


final Gate gate = new Gate();

new UserThread(gate,"aaa", "bbb").start();

new UserThread(gate,"ccc", "ddd").start();

new UserThread(gate,"eee", "fff").start();

}

}



'Development > Programming' 카테고리의 다른 글

[Java Design Patten] Guarded Suspension  (0) 2014.05.31
[Java Design Patten] Immutable  (0) 2014.05.23
[Java] wait, notify, notifyAll  (0) 2014.05.16
[Java] synchronized 사용법 정리  (0) 2014.05.16
[Java] 패키지 탐색하기~!  (0) 2014.04.17