java: wait(), notify() and synchronized blocks

拥有回忆 提交于 2019-11-30 13:28:30
  1. notify will wake one thread waiting on the monitor. Unless and until the monitor is unowned, no thread waiting can run; wait() must be called in a synchronized block and so the lock must be held to continue running that block.
  2. No guarantees. Call notifyAll to give all threads a chance to wake.
  3. Dunno. You could have the thread set a variable saying it's waiting before it goes to sleep...
  4. This is probably a bad idea. Can you come up with a situation where this is necessary?

When you call wait() from a thread, that thread stop executing and it's added to the waitset of the object. When you call notify() from another thread, a random thread from the waitset is waked up, if you call notifyAll() all would be ready to execute.

When you call notify(), the thread is ready to run but it doesnt mean it will be executed inmediately so be careful.

  1. It would wake up a thread from the waitset randomly.

  2. Youd don't know which one will be waked up first, it doesn't follow any order.

  3. Thread.getState()

  4. You would produce deadlock.

  1. That's why you have the notify() and notifyAll() methods. The former wakes up one thread waiting on the object, the latter wakes up all threads. A waiting thread will not wake up if wait() is called in another thread.

  2. No.

  3. It's only possible to call thread.holdsLock(obj) to see if a thread holds the monitor lock on a particular object.

  4. Don't call wait() in a finalize method.

2: Not necessarily. notify() wakes up one of the waiting threads. It might be the original one or the third one.

3: Using thread.getState() you can find out if a thread is waiting for an object, but I don't know if you can always find out which object this is, exactly.

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