我无法理解这些方法,还有变量空:
private String message;
private boolean empty = true;
public synchronized String read() {
while (empty) {
try {
wait();
} catch (InterruptedException e) {}
}
empty = true; // i mean this line
notifyAll();
return message;
}
public synchronized void write(String message) {
while (!empty) {
try {
wait();
} catch (InterruptedException e) {}
}
empty = false; // and this line
this.message = message;
notifyAll();
}
首先我不能很好地理解wait()和notifyAll(),其次为什么在read()中的while循环之后,空是真,为什么不是假呢? 与 write() 相同,为什么在 while 循环后不为 true?
抱歉,如果我的语言不好,我不是母语人士。
最佳答案
它的顺序有点奇怪 - 例如,我会在修改“message”后修改“empty”,对我来说似乎更明显 - 但是...
这是一个单消息缓冲区。
“write”方法会等待“empty”,此时它可以将消息设置为“message”,使其不为空。
“read”方法会等待,直到“notempty”,此时它可以使用“message”中的消息,使其再次为空。
根据我的口味,变量“empty”是多余的。我将其基于“消息”的 null/非 null 状态(假设永远不会将 null 写入消息)。
关于java - 为什么 while 循环后 boolean 变量仍然为 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61261167/