Wednesday, May 4, 2016

Simply WOW : Java Multi-threading wait return sequence


Many programmers
believe (incorrectly) that wait() returns as soon as the notify is issued, but that's simply not the case.
The wait() call doesn't return until the method that calls notify() releases the monitor.
Remember, you must be in the monitor to call either method. In the following code, wait() won't

return until the read() operation completes:



package lrxjava;

public class Dysfunctional {



public synchronized void reader()

System.out.println("Current time in nano  :" + System.currentTimeMillis());
notify();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

}

public synchronized void wait_for_read()


System.out.println("Current time in nano in wait :" + System.currentTimeMillis());
try {
wait();
System.out.println("Current time in nano in wait :" + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
Dysfunctional dysfunctional = new Dysfunctional();

Runnable task2 =   ()->dysfunctional.wait_for_read();
new Thread(task2).start();

Runnable task =   ()->dysfunctional.reader();
new Thread(task).start();

}
}