gpt4 book ai didi

java - 为什么我的release()方法没有唤醒我的实例?

转载 作者:行者123 更新时间:2023-12-02 07:05:56 25 4
gpt4 key购买 nike

我编写了一个示例程序来演示我的问题。有一个调酒师线程和三个顾客线程。它们一旦创建就同时运行。调酒师应该为每位顾客提供一杯饮料。

我的问题是 Bartender 类 run() 方法中的 wait() 方法永远不会唤醒。我本来打算在每个 Customer 类的 run() 方法中使用 release() 方法来唤醒它,但它似乎不起作用。它永远不会醒来。

我该如何解决这个问题?感谢任何可以提供建议或代码片段的人。

import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Bar {

Semaphore serving;
boolean isServing = false;

public static void main(String[] args) {
Bar bar = new Bar();
bar.run();
}

public void run() {
serving = new Semaphore(1);
Thread bartender = new Thread(new Bartender());
bartender.start();
threadSleep(1000);

Thread customer1 = new Thread(new Customer());
customer1.start();
threadSleep(2000);
Thread customer2 = new Thread(new Customer());
customer2.start();
threadSleep(2000);
Thread customer3 = new Thread(new Customer());
customer3.start();
}

public void threadSleep(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException ex) {
Logger.getLogger(Bar.class.getName()).log(Level.SEVERE, null, ex);
}
}

public class Bartender implements Runnable {
public void run() {
while (true) {
if (serving.availablePermits() == 0) {
synchronized (this) {
try {
System.out.println("Waiting for Customer notify");
wait();
System.out.println("Serve drink");
} catch (InterruptedException ex) {
Logger.getLogger(Bar.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
}

public class Customer implements Runnable {
private boolean customerServed = false;

public void run() {
if (!customerServed) {
synchronized (this) {
try {
serving.acquire();
if (serving.availablePermits() == 0 && !serving.hasQueuedThreads()) {
notify();
isServing = true;
System.out.println("Customer: Recieves drink");
customerServed = true;
serving.release();
isServing = false;
}
} catch (InterruptedException ex) {
Logger.getLogger(Bar.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
}

最佳答案

调酒师类客户类

synchronized (this) { 更改为 synchronized (Bar.this) {

wait() 更改为 Bar.this.wait()

notify() 更改为 Bar.this.notify()

因为两个 this 引用不同的对象,Bartender 永远不会醒来。并且因为两个 Bar.this 引用同一个对象,Bartender 将会醒来!

关于java - 为什么我的release()方法没有唤醒我的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16116813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com