在这篇文章中,我们将看到为什么 wait(),notify()和notifyAll()方法 在对象类而不在线程类中。
这是最常问的问题之一 爪哇 多线程面试题.
You might know that wait()
, notify()
And notifyAll()
Methods are in Object class and do you know the reason for the same?
让’讨论为什么wait(),notify()和notifyAll()方法在对象类中。
In 爪哇 , 线 waits
on 监控 assigned to the object and when you want to send a signal to another 线 who is waiting for the same 监控, you call notify()
method to wake
one 线 and notifyAll() to wake up all the 线 s.
如果等待,则notify和notifyAll方法在线程类中,则每个 线 应该知道另一个线程的状态。
例如:’s说您有两个线程,T1和T2。现在T1必须知道T2正在等待我刚刚释放的这个特定资源,因为T1将需要调用T2.notify()。
在Java中, 对象本身是共享的 在线程之间并促进 线程间通讯. 线程彼此之间没有特定的知识。它们可以异步运行并且是独立的。他们只是运行,锁定,等待并得到通知。他们不需要了解其他线程的状态。他们只需要在一个对象上调用notify方法,因此将通知正在该资源上等待的线程。
如前所述,
- When you call
wait()
method on the object, then it gives up 监控 and go to 睡觉 - When you call
notify()
method, then the single 线 which is waiting for the object’的监视器将被通知。
因此,请等待,notify()和notifyAll()在对象上工作’的监视器级别。如果当前持有监视器的线程要放弃监视器,则它将在对象上调用wait方法,如果要通知其他线程,则将在对象上调用notify方法。
Shared objects allow 线 s to communicate by calling wait()
, notify()
And notifyAll()
Methods, so these methods are in the object class.
那’关于为什么wait(),notify()和notifyAll()方法在对象类中而不在线程类中的所有信息。
很好的解释