ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋™๊ธฐํ™” ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ์„ธ๋งˆํฌ์–ด ์™ธ์— ๊ณ ์ˆ˜์ค€์ธ ๋ชจ๋‹ˆํ„ฐ๋ผ๋Š” ๋ฐฉ์‹์ด ์žˆ๋‹ค. ์šด์˜์ฒด์ œ์—์„œ๋Š” mutex๋ฅผ ์ œ๊ณตํ•˜์ง€๋งŒ ์ž๋ฐ”์—์„œ๋Š” ๋ชจ๋‹ˆํ„ฐ๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋™๊ธฐํ™”์— ๋Œ€ํ•œ ๋ฌธ์ œ๋ฅผ ์‰ฝ๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค. ๋ชจ๋‹ˆํ„ฐ ๋ฐฉ์‹์€ synchronized๋ฅผ ํ†ตํ•ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 ์ž๋ฐ”์—์„œ ์„ธ๋ชจํฌ์–ด ๊ฐ์ฒด๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ, ์ดˆ๊ธฐ์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ์“ฐ๋ ˆ๋“œ์˜ ์ˆ˜๋ฅผ ์ ์ ˆํžˆ ์ง€์ •ํ•ด์ฃผ๊ณ  ์ด๋ฅผ ํŒ๋‹จํ•˜์—ฌ acquire, releaseํ•˜์—ฌ์•ผ ํ•œ๋‹ค. ํ•˜์ง€๋งŒ synchroronized๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ณด๋‹ค ๊ฐ„ํŽธํ•˜๊ฒŒ ๋™๊ธฐํ™”๋ฅผ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.

 

BankAccount Problem (USE synchronized)

class BankAccount {
    int balance;
    boolean p_turn = true;
    synchronized void deposit(int amount) {
        int temp = balance + amount;
        System.out.print("+");
        balance = temp;
        notify();
        p_turn = false;
        try {
            wait();
        } catch (InterruptedException e) {}
    }
    synchronized void withdraw(int amount) {
        while (p_turn)
            try {
                wait();
            } catch (InterruptedException e) {}
        int temp = balance - amount;
        System.out.print("-");
        balance = temp;
        notify();
        p_turn = true;
    }
    int getBalance() {
        return balance;
    }
}

class Parent extends Thread {
    BankAccount b;
    int count;

    Parent(BankAccount b, int count) {
        this.b = b;
        this.count = count;
    }
    public void run() {
        for (int i = 0; i < count; i++)
            b.deposit(1);
    }
}

class Child extends Thread {
    BankAccount b;
    int count;

    Child(BankAccount b, int count) {
        this.b = b;
        this.count = count;
    }
    public void run() {
        for (int i = 0; i < count; i++)
            b.withdraw(1);
    }
}

class Test {
    static final int MAX = 100;
    public static void main(String[] args) throws InterruptedException {
        BankAccount b = new BankAccount();
        Parent p = new Parent(b, MAX);
        Child c = new Child(b, MAX);
        p.start();
        c.start();
        p.join();
        c.join();
        System.out.println( "\nbalance = " + b.getBalance());
    }
}

 ์„ธ๋ชจํฌ์–ด๋ฅผ ํ†ตํ•ด ํ•ด๊ฒฐ ํ•˜์˜€๋˜ ์€ํ–‰ ๊ณ„์ขŒ ๋ฌธ์ œ๋ฅผ synchronized๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ์„œ ์‰ฝ๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค. ์ž„๊ณ„ ๊ตฌ์—ญ์— ํ•ด๋‹น ํ•˜๋Š” deposit, withdraw์— synchrozined๋ฅผ ๋ถ™์ด๊ฒŒ ๋˜๋ฉด ์ž„๊ณ„ ๊ตฌ์—ญ์— ๋™์‹œ์— ์ ‘๊ทผํ•˜๋Š” ๋ฌธ์ œ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค์ง€ ์•Š๋Š”๋‹ค.

 synchronized๋Š” wait(), notify() ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ฐ๊ฐ์˜ ์—ญํ• ์€ ํŠน์ • ์Šค๋ ˆ๋“œ๊ฐ€ wait() ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด, ๋‹ค๋ฅธ ์“ฐ๋ ˆ๋“œ๋กœ ๋ถ€ํ„ฐ notify() ๋  ๋•Œ๊นŒ์ง€ ์“ฐ๋ ˆ๋“œ๋Š” ๋Œ€๊ธฐ์ƒํƒœ๊ฐ€ ๋œ๋‹ค. ์ด๋ฅผ ์ž„๊ณ„ ๊ตฌ์—ญ์— ํ™œ์šฉํ•˜๋ฉด, ๊ฐ ์“ฐ๋ ˆ๋“œ์— ๋Œ€ํ•œ ์‹คํ–‰ ์ˆœ์„œ๋„ ๋ณด์žฅํ•  ์ˆ˜ ์žˆ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€