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

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

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

[ ] 자바의 정석 기초편 카테고리
chapter 13 쓰레드

chapter 13-32 synchronized를 이용한 동기화 예제1
예제 13-12

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

class Ex13_12 {
	public static void main(String args[]) {
    	Runnable r = new RunnableEx12();
        new Thread(r).start(); // ThreadGroup에 의해 참조되므로 gc대상이 아니다.
        new Thread(r).start(); // ThreadGroup에 의해 참조되므로 gc대상이 아니다.
    }
}

class Account {
	private int balane = 1000;
    
    public 	int getBalance() {
    	return balance;
    }
    
    public void withdraw(int money) {
    	if(balance >= money) {
        	try { Thread.sleep(1000);} catch(InterruptedException e) {}
        }
    } // withdraw
}

class RunnableEx12 implements Runnable {
	Account acc = new Account();
    
    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_12 {
// Ex13_12 클래스 선언
	public static void main(String args[]) {
    // 접근제어자 public으로 메모리에 상주하게 리턴값이 없이 main 메서드 선언
    	Runnable r = new RunnableEx12();
        // Runnable 클래스의 객체 r를 선언하고 생성자로 초기화한다.
        new Thread(r).start(); // ThreadGroup에 의해 참조되므로 gc대상이 아니다.
        new Thread(r).start(); // ThreadGroup에 의해 참조되므로 gc대상이 아니다.
    }
}

class Account {
	private int balane = 1000;
    
    public 	int getBalance() {
    	return balance;
    }
    
    public void withdraw(int money) {
    	if(balance >= money) {
        	try { Thread.sleep(1000);} catch(InterruptedException e) {}
        }
    } // withdraw
}

class RunnableEx12 implements Runnable {
	Account acc = new Account();
    
    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()
}

 

반응형