package com.basic;//스레드 동기화 Synchronized
class ATM implements Runnable{
//공유 자원
private long depositeMoney = 10000;
public void run(){
synchronized (this){
for(int i=0;i<5;i++){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
if(getDepositeMoney() <= 0)
break;
//임계 영역 : 공유자원을 변경하는 코드영역
withDraw(1000);
}
}
}
public void withDraw(long howMuch){
if(getDepositeMoney()>0){
depositeMoney -= howMuch;
System.out.println(Thread.currentThread().getName()+" , "+getDepositeMoney());
}else{
System.out.print(Thread.currentThread().getName()+" , ");
System.out.println("잔액이 부족하다");
}
}
public long getDepositeMoney(){
return depositeMoney;
}
}
public class SynchronizedEx {
public static void main(String[] args) {
ATM atm = new ATM();
Thread mother = new Thread(atm,"mother");
Thread son = new Thread(atm,"son");
mother.start();
son.start();
}
}
mother , 9000
mother , 8000
mother , 7000
mother , 6000
mother , 5000
son , 4000
son , 3000
son , 2000
son , 1000
son , 0
'Java > Thread' 카테고리의 다른 글
| swing으로 디지털 시계 만들기 (1) | 2012.04.11 |
|---|---|
| Thread Priority (0) | 2012.04.11 |
| Multi-Thread (0) | 2012.04.11 |
| Thread runnable (0) | 2012.04.11 |
| Thread(스레드,쓰레드) (0) | 2012.04.11 |