Java/Thread
Thread synchronization(스레드 동기화)
Bohemian life
2012. 4. 11. 23:03
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