我是在 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();
}
}