본문 바로가기
프로그래밍/자바의 정석 기초편 코드 분석

자바의 정석 기초편 코드 분석 137(예제 13-13)

by 리드민 2023. 9. 26.
반응형

[ ] 자바의 정석 기초편 카테고리
chapter 13 쓰레드
chapter 13-33 synchronized를 이용한 동기화 예제2
예제 13-13


[ ] 코드 분석
1. 원본 코드

class Ex13_13 {
	public static void main(String args[]) {
    	Runnalbe r = new RunnableEx13();
        new Thread(r).start();
        new Thread(r).start();
    }
}

class Account2 {
	private int balance = 1000; // private으로 해야 동기화가 의미가 있다.
    
    public int getBalance() {
    	return balance;
    }
    
    public synchronized void withdraw(int money){ // synchronized로 메서드를 동기화
    	if(balance >= money) {
        	try { Thread.sleep(1000);} catch(InterruptedException e) {}
            balance -= money;
        }
    } //withdraw
}

class RunnableEx13 implements Runnable {
	Account2 acc = new Account2();
    
    public void run() {
    	while(acc.getBalance() > 0) {
        	// 100, 200, 300중의 한 값을 임의로 선택해서 출금(withdraw)
            int money = (int)(Math.random() * 3 + 1) * 100;
            acc.withdraw(money);
            System.out.println("balance:"+acc.getBalance());
        }
    } // run()
}


2. 해석본

class Ex13_13 {
// Ex13_13 클래스 선언
	public static void main(String args[]) {
    // 접근제어자 public으로 메모리에 상주하게 리턴값이 없이 main 메서드 선언
    	Runnalbe r = new RunnableEx13();
        // Runnalbe 클래스의 인스턴스 r 선언하고 
        new Thread(r).start();
        new Thread(r).start();
    }
}

class Account2 {
// Account2 클래스 선언
	private int balance = 1000; // private으로 해야 동기화가 의미가 있다.
    
    public int getBalance() {
    // 접근제어자가 public이고 반환값이 int형인 getBalance() 선언
    	return balance;
        // balance 값 리턴
    }
    
    public synchronized void withdraw(int money){ // synchronized로 메서드를 동기화
    	if(balance >= money) {
        // if문 선언
        	try { Thread.sleep(1000);} catch(InterruptedException e) {}
            balance -= money;
        }
    } //withdraw
}

class RunnableEx13 implements Runnable {
// Runnable 클래스 상속 클래스 RunnableEX13 선언
	Account2 acc = new Account2();
    // Account2 클래스의 인스턴스 acc 선언 Account2()
    
    public void run() {
    	while(acc.getBalance() > 0) {
        	// 100, 200, 300중의 한 값을 임의로 선택해서 출금(withdraw)
            int money = (int)(Math.random() * 3 + 1) * 100;
            // int형 변수 money 선언
            acc.withdraw(money);
            // acc 인스턴스의 함수 withdraw 선언
            System.out.println("balance:"+acc.getBalance());
        }
    } // run()
}
반응형