I have two threads t0 and t1 with runnables posted below in the code section Run_0 and Run1 respectively. what I want to do is, when t0 is writing or doing its task that lasts for 7 seconds, t1 should be waiting. and when the 7 seconds elapse, t1 should be notified to continue working. I tried to do that using wait() and notify() but at run time I receive the below posted errors.
please let me know how to use wait() and notify() correctly
code:
public static void main(String[] args) {
t0 = new Thread(new Run_0());
t1 = new Thread(new Run_1());
t0.start();
t1.start();
}
private static class Run_0 implements Runnable {
public void run() {
// TODO Auto-generated method stub
while (true) {
long startTime = TimeUtils.getTSSec();
synchronized (this) {
try {
t1.wait(); //<=========Line 27
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("T0 is writing");
//simulate doing some work
while( (TimeUtils.getTSSec()-startTime) <= 7) {
}
System.out.println("T0 finished writing");
t1.notify();
startTime = TimeUtils.getTSSec();
while( (TimeUtils.getTSSec()-startTime) <= 7) {
}
}
}
}
private static class Run_1 implements Runnable {
public void run() {
// TODO Auto-generated method stub
while(true) {
System.out.println("T1 is working");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
errors:
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Unknown Source)
at com.example.Main$Run_0.run(Main.java:27)
at java.lang.Thread.run(Unknown Source)