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

南楼画角 提交于 2019-12-02 11:28:32

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.

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();
   }
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!