我有一个理解这些方法的问题,还有变量空:
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循环之后,empty为true,为什么不为false?与write()相同,为什么在while循环后不成立?
抱歉,如果我的语言不好,我不是母语。在此先感谢
这有点奇怪-例如,我在修改'消息'之后会修改'空',对我来说似乎更明显-但...
这是一个消息缓冲区。
'write'方法一直等到'empty'为止,此时它可以将消息设置为'message',使其不为空。
'读取'方法一直等待到'不为空',此时它可以使用'消息'中的消息,使其再次为空。
根据我的口味,变量“空”是多余的。我将其基于'message'的null / non-null状态(假设永远不会出现将null作为消息写的情况)。
read
调用wait
,只要empty
为真:表示没有要读取的内容。一旦empty
为假,read
会将empty
设置为true(表示它读取了要读取的内容),通知任何等待的线程,然后返回。
write
完全相反。