【发布时间】:2013-08-26 13:31:00
【问题描述】:
我不熟悉在 java 中使用线程。我有一个简单的读写器问题,当作者进入线程时,读者将等待作者完成。
但是,当我运行我的程序时,我发现我的线程没有得到通知?这是为什么呢?
我的代码如下:
public class ReaderWriter {
Object o = new Object();
volatile boolean writing;
Thread readerThread = new Thread( "reader") {
public void run() {
while(true) {
System.out.println("reader starts");
if(writing) {
synchronized (o) {
try {
o.wait();
System.out.println("Awaked from wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println( "reader thread working "+o.hashCode());
}
}
};
Thread writerThread = new Thread("writer" ) {
public void run() {
System.out.println( " writer thread");
try {
synchronized (o) {
writing = true;
System.out.println("writer is working .. ");
Thread.sleep(10000);
writing = false;
o.notify();
System.out.println("reader is notified");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
public static void main(String[] args) {
ReaderWriter rw=new ReaderWriter();
rw.readerThread.start();
rw.writerThread.start();
}
}
【问题讨论】:
-
你得到的输出是什么?您期望的输出是什么?
-
@BrentWorden 我希望读者“从等待中醒来”,但程序不会终止
-
@Achyut 我也有同样的问题。我放弃并使用了 notifyAll();这不是答案,而是一种解决方法
-
@BrentWorden 在我的情况下 notifyAll 也不起作用
-
好吧,reader-thread 得到了通知,但是程序并没有终止,因为 reader-thread 是一个无限循环。
标签: java multithreading wait notify