我已经尝试解决了两天,现在我终于放弃了,我在这里发布代码,希望有人能为我提供我所缺少的东西,因为我想我很亲近,请帮助!

理发师的代码:

public Semaphore customer = new Semaphore(0);
public Semaphore barber = new Semaphore(0);
public Semaphore accessSeats = new Semaphore(1);
public int freeChairs = 5;

@Override
public void run() {
    while (true) {
        try {
            customer.acquire(); //it seems the barber never acuires a customer, even after the semaphore is released
            accessSeats.acquire();
            freeChairs += 1;
            cutHair();
            barber.release();
            accessSeats.release();
        } catch (InterruptedException ex){}

客户代码:
    public void run() {
    while (notCut) {
        try {
            bs.accessSeats.acquire();
        } catch (InterruptedException ex) {}
        if (bs.freeChairs > 0) {
            bs.freeChairs -= 1;
            bs.customer.release();
            bs.accessSeats.release();
            try {
                bs.barber.acquire(); //the customer cant get past this line
                getHaircut();
            } catch (InterruptedException ex) {}
        } else {
            bs.accessSeats.release();
            notCut = false;
        }
    }
}

我在一个随机计时器上创建1个理发师和100个客户。

编辑:cutHair()将理发器线程 sleep 1-5秒(随机)。和getHaircut()仅打印一条消息,并设置notCut=false;

最佳答案

Semaphore 是一个计数信号量-您应该阅读Javadoc以获得更多信息。问题是您永远不会告诉barber Semaphore有可用的Barber。因此,它将永远不允许Customer来获取它。

解决方案:
创建Barber时,要做的第一件事是调用barber.release()(在while循环之前!)或使用1个许可初始化barber

10-04 12:19