我知道类似的问题已经被问了很多次,但我花了一些时间阅读类似的问题,找不到一个正确的答案。
代码如下:
public class Main {
public static void main(String[] args) {
Message message = new Message();
(new Thread(new Writer(message))).start();
(new Thread(new Reader(message))).start();
}
}
class Message {
private String message;
private boolean empty = true;
public synchronized String read() {
while(empty) {
try {
System.out.println("Reader is waiting...relinquish the lock");
wait();
} catch(InterruptedException e) {
}
}
empty = true;
notifyAll();
return message;
}
public synchronized void write(String message) {
while(!empty) {
try {
System.out.println("Writer is waiting...relinquish the lock");
wait();
} catch(InterupptedException e) {
}
}
empty = false;
this.message = message;
notifyAll();
}
}
class Writer implements Runnable {
private Message message;
public Writer(Message message) {
this.message = message;
}
public void run() {
String messages[] = {
// some message here
};
for(int i=0; i < messages.length; i++) {
message.write(messages[i]);
}
message.write("Finished");
}
}
class Reader implements Runnable {
private Message message;
public Reader(Message message) {
this.message = message;
}
public void run() {
for(String msg = message.read(); !msg.equals("Finished"); msg = message.read()) {
System.out.println(msg);
}
}
我的理解是,在reader线程的for循环中返回一个read()方法后,标志empty变为true,writer线程被notifyall()唤醒并准备运行,但reader尚未放弃对message对象的锁定,这意味着writer无法调用synchronized write()方法,因为它仍然被阻止。然后读取器线程应该再次调用read(),进入while循环,打印出“reader is waiting…”消息,然后调用wait()放弃锁,这样writer线程就可以继续获取锁并调用write()方法。
但是从控制台显示的输出消息来看,很多时候“reader is waiting…”消息根本没有被打印出来,只有几次被打印出来。从上面的推理来看,这个消息不应该在每次程序运行时都被打印出来吗?
暂无答案!
目前还没有任何答案,快来回答吧!