notify, wait
2019. 8. 16. 12:29ㆍ프로그래밍/Java
class ATM implements Runnable{
private long depositeMoney = 10000;
public void run(){
synchronized(this) {
for(int i=0; i<10; 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()+",");
System.out.println("잔액: " + getDepositeMoney()+"\n");
} else {
System.out.println(Thread.currentThread()+",");
System.out.println("잔액이 부족합니다.");
}
}
public long getDepositeMoney() {
return depositeMoney;
}
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();
}
}
class ATM implements Runnable{
private long depositeMoney = 10000;
public void run(){
synchronized(this) {
for(int i=0; i<10; i++) {
notify(); // 실행 대기상태로 만듬
try {
wait(); //일시 정지 상태로 만듬
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()+",");
System.out.println("잔액: " + getDepositeMoney()+"\n");
} else {
System.out.println(Thread.currentThread()+",");
System.out.println("잔액이 부족합니다.");
}
}
public long getDepositeMoney() {
return depositeMoney;
}
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();
}
}
정상 작동