I have two streams. In one thread that started immediately there is such a code.

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

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

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

Can it happen that both threads will be in wait ? Such a question I was asked at the interview, I said that I could not, I was told you were mistaken, think. Who was right? Java dock on my side, but still wanted to clarify. Can you give an example of a situation where both threads will be in a wait at the same time, due to some reasons? The first thing that comes to mind on the second question is to change the wait and notify in the second thread in some places.

  • @zRrr But I have little idea about this situation, even if I rigidly tie the thread to the core, show it the minimum priority and load this core with high priority threads, is there any chance of such an outcome? Is it possible to read about this in Jawadok? - Ivan Gladush
  • one
    I do not think that in JavaDoc about it will be written. It is a general concept of multithreading that threads run in parallel without a prescribed order in time. Those. you cannot guarantee 100% in your example that the first wait will work before notify. In practice, there will be no problems, but theoretically you cannot be 100% sure. PS in the code still need to add synchronized and try / catch - Russtam
  • @zRrr would be great if you could formulate and leave an answer to this question - Ivan Gladush
  • @zRrr still write, please, step by step - how can this be. - dSH

1 answer 1

The most simple answer I think is the following. If the system is heavily loaded, even if the first thread is started 10 seconds earlier, this does not mean that it will capture the monitor first and the synchronized block will enter (it may be that the priority tasks on the computer are performed before). Accordingly, a situation is possible when the second stream is captured by the monitor first. Therefore, the second thread can execute MONITOR.notify (); then, when MONITOR.wait () was not called on the first thread; Because of this, both threads go to wait.