【发布时间】:2020-07-30 08:06:00
【问题描述】:
我对这些方法理解有问题,还有变量empty:
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 循环之后不为真?
对不起,如果我的语言不好,我不是母语人士。
【问题讨论】:
-
想象一下,如果
empty被重命名为messageConsumed。是不是更清楚了? -
@VGR 还没有,为什么在 while 循环块之后,在 write() 中仍然正确?
-
因为
write方法必须等待消息被读取。一旦被读取,布尔字段设置为 false,表示有新消息可供阅读。
标签: java multithreading concurrency wait notify