Java
Thread Synchronization
GOD03219
2017. 12. 29. 13:20
public class Test01 implements Runnable {
private int pay;
public Test01() {
pay = 10000;
}
@Override
public synchronized void run() {
for(int i=0; pay!=0 ;i++){
try{
Thread.sleep(1000);
pay-=1000;
System.out.print(Thread.currentThread().getName());
System.out.println(" 현재금액 : " +pay);
// 이 두 개의 메소드는 동기화 처리에서만 사용가능
notify(); // son Thread에게 넘겨줌
wait(); // wait를 나중에 선언, mom Thread는 멈춤
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Test01 th = new Test01();
Thread mom = new Thread(th,"Mom"); // 두 개의 스레드가 하나의 자원(th) 공유
Thread son = new Thread(th,"Son");
mom.start();
son.start();
}
}