java – Can all applications run if I use one monitor?


I have two threads. In one thread that started immediately, there is such code

public void run(){ MONITOR.wait(); ...}

In the second thread, which starts 10 seconds after the first, the following code:

public void run(){ MONITOR.notify(); MONITOR.wait();...}

Is it possible that both threads will be in wait ? I was asked such a question at an interview, I said that I couldn’t, I was told you were mistaken, think. Who was right? Java doc is on my side, but I still wanted to clarify. Can you give an example of a situation where both threads will be in wait at the same time, due to some reason? The first thing that comes to mind for the second question is to swap wait and notify in the second thread.


The simplest answer, in my opinion, is the following. If the system is heavily loaded, then even if the first thread is launched 10 seconds earlier, this does not mean that it will be the first to capture the monitor and the synchronized block will enter (before that, higher priority tasks on the computer may be performed). Accordingly, a situation is possible when the second thread captures the monitor first. Therefore, the second thread can execute MONITOR.notify(); when MONITOR.wait() has not yet been called on the first thread; As a result, both threads go to wait.

Scroll to Top