잠자는 이발사- 생산자 소비자 문제

Jeong·2023년 4월 4일
0
post-custom-banner

https://ko.wikipedia.org/wiki/%EC%9E%A0%EC%9E%90%EB%8A%94_%EC%9D%B4%EB%B0%9C%EC%82%AC_%EB%AC%B8%EC%A0%9C

잡자는 이발사 문제 Java 구현

import java.util.concurrent.Semaphore;

class Chair {
    int[] cha;
    int size;
    int waitCustomer;
    int in;
    int out;
    Semaphore cust;
    Semaphore barb;

    Chair(int size) {
        cha = new int[size];
        this.size = size;
        waitCustomer = in = out = 0;
        cust = new Semaphore(size);
        barb = new Semaphore(0);
    }

    void down(int customer) {
        if (waitCustomer == size) {
            System.out.println("---Watting Chair is Full---");
        }
        try {
            cust.acquire();
            System.out.println("Customer" + customer + ": sit on the WatingChair...");
            cha[in] = customer;
            in = (in + 1) % size;
            waitCustomer += 1;
            barb.release();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    void up() {
        if (waitCustomer == 0) {
            System.out.println("Barber: sleeping");
        }
        try {
            barb.acquire();
            System.out.println("Customer" + cha[out] + ": move");
            out = (out + 1) % size;
            waitCustomer -= 1;
            cust.release();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

    }
}

class Customer extends Thread {
    Chair cha;
    int totalCustomer;

    Customer(Chair cha, int totalCustomer) {
        this.cha = cha;
        this.totalCustomer = totalCustomer;
    }

    @Override
    public void run() {
        for (int i = 0; i < totalCustomer; i++) {
            cha.down(i);
        }
    }
}

class Barber extends Thread { // 소비자
    Chair cha;
    int totalCustomer;

    Barber(Chair cha, int totalCustomer) {
        this.cha = cha;
        this.totalCustomer = totalCustomer;
    }

    void getHairCut() {
        System.out.println("Barber: HairCut-----");
    }

    @Override
    public void run() {
        for (int i = 0; i < totalCustomer; i++) {
            cha.up();
            getHairCut();
        }
    }

}


class SleepingBarber {
    public static void main(String[] args) {
        Chair chair = new Chair(3);
        Customer customer = new Customer(chair, 7);
        Barber barber = new Barber(chair, 7);

        customer.start();
        barber.start();
    }
}
profile
화이팅!!
post-custom-banner

0개의 댓글