gpt4 book ai didi

java - wait() 是一个 "if" block 或一个 "while" block

转载 作者:行者123 更新时间:2023-12-04 22:12:35 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Why should wait() always be called inside a loop

(11 个回答)


7年前关闭。




以下代码复制自 http://www.programcreek.com/2009/02/notify-and-wait-example/

我已经看到了很多使用 while 循环来包装 wait() 的示例

我的问题:
在我第一次尝试解决类似问题时,我使用 if 语句来包装 wait()。例如,

if(messages.size() == MAXQUEUE) {
wait();
}

使用 while 循环代替 if 语句有什么好处?
import java.util.Vector;

class Producer extends Thread {

static final int MAXQUEUE = 5;
private Vector messages = new Vector();

@Override
public void run() {
try {
while (true) {
putMessage();
//sleep(5000);
}
} catch (InterruptedException e) {
}
}

private synchronized void putMessage() throws InterruptedException {
while (messages.size() == MAXQUEUE) {
wait();
}
messages.addElement(new java.util.Date().toString());
System.out.println("put message");
notify();
//Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object.
}

// Called by Consumer
public synchronized String getMessage() throws InterruptedException {
notify();
while (messages.size() == 0) {
wait();//By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep.
}
String message = (String) messages.firstElement();
messages.removeElement(message);
return message;
}
}

class Consumer extends Thread {

Producer producer;

Consumer(Producer p) {
producer = p;
}

@Override
public void run() {
try {
while (true) {
String message = producer.getMessage();
System.out.println("Got message: " + message);
//sleep(200);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String args[]) {
Producer producer = new Producer();
producer.start();
new Consumer(producer).start();
}
}

最佳答案

即使您没有主动通知正在等待的对象,wait() 也可能返回(这在 documentation 中称为“虚假唤醒”)。这就是为什么将 wait() 调用包装到一个 while 循环中更有意义,该循环检查是否满足您想要等待的实际条件,如果不满足则再次调用 wait(),而不是简单地假设何时 wait( ) 返回您实际等待的事件已经发生。

关于java - wait() 是一个 "if" block 或一个 "while" block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22852760/

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