Can a thread call wait() on two locks at once in Java (6)

后端 未结 2 1310
眼角桃花
眼角桃花 2021-01-28 01:58

I\'ve just been messing around with threads in Java to get my head around them (it seems like the best way to do so) and now understand what\'s going on with synchronize, wait()

相关标签:
2条回答
  • 2021-01-28 02:32

    The example doesn't include the condition upon which the waiting will be performed. Typically, waiting will occur only and until the condition has been met. Generally, I would think that one could accomplish what you are trying to by having a single lock / wait and abstracting the 'token1 and token2' into the conditional logic.

    For example

    synchronized(object) {
       while ((!token1ConditionMet) && (!token2ConditionMet)) {
           wait();
       }
    } 
    
    0 讨论(0)
  • 2021-01-28 02:46

    No, not with a standaad Java lock. Although I guess you could construct such a lock.

    wait should be called within a while loop (wait may spuriously wakeup, and in most situations you would want the loop anyway). So some kind of flag would make more sense.

    0 讨论(0)
提交回复
热议问题