Java threads: wait and notify methods

后端 未结 7 1554
遥遥无期
遥遥无期 2020-12-04 00:28

I have a thread that calls the wait method and can only be awoken when the notify method called from some other class:

 class Threa         


        
相关标签:
7条回答
  • 2020-12-04 00:52

    It is possible for ThreadB's run method to complete before you enter the synchronized block in ThreadA.main. In that situation, since the notify call has happened before you started waiting, ThreadA will block forever on the wait call.

    A simple workaround would be to grab the lock on b in main before you start the second thread to ensure the wait happens first.

    ThreadB b = new ThreadB();
    synchronized(b) {
        b.start();
        ...
        b.wait();
    }
    
    0 讨论(0)
提交回复
热议问题