本文介绍了java:wait(),notify()和synchronized块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到调用Object的 wait()方法将释放对象监视器(如果存在)。

I learned that calling an Object's wait() method will release the object monitor, if present.

但我有一些关于在另一个线程上对此对象调用 notify()的问题:

But I have some questions regarding calling notify() on this object by another thread:


  1. (何时)如果另一个(第3个)线程同时拥有对象监视器,则等待线程会被唤醒吗?

  1. (when) will the waiting thread wake up, if another (a 3rd) thread owns the object monitor in the meanwhile?

等待线程唤醒,如果第三个线程在这个对象上叫 wait()

will the waiting thread wake up, if a 3rd thread called wait() on this object?

是不是可以确定线程是否在等待通知特定对象(java 1.4 / java 5)

is it possible to determine if a thread is waiting for notifying a particular object (java 1.4/java 5)

如果 wait()会发生什么将在 finalize()方法中调用?


推荐答案


  1. notify 将唤醒一个在监视器上等待的线程。除非直到监视器无主,否则不能运行任何线程;必须在同步块中调用wait(),因此必须保持锁定才能继续运行该块。

  2. 无保证。调用 notifyAll 给所有线程偶然唤醒。

  3. Dunno。你可以让线程设置一个变量,说它在等待它进入睡眠状态之前等待...

  4. 这可能是一个坏主意。你能想出一个必要的情况吗?

  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?

这篇关于java:wait(),notify()和synchronized块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 18:54