I am new to using threads in java . I have a simple reader writer problem where that when a writer comes in on a thread, a reader will wait for the writer to complete.
However, when I run my program, I find that my thread doesn't get notified? Why is this?
My code is below:
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();
}
}