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();

		}

	}

 

정상 작동

'프로그래밍 > Java' 카테고리의 다른 글

네트워크  (0) 2019.08.16
예외 처리기  (0) 2019.08.16
쓰레드  (0) 2019.08.16
제네릭  (0) 2019.08.15
anonymous class  (0) 2019.08.15