Java notify(),notifyAll()和wait()方法 [英] Java notify(), notifyAll() and wait() methods

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

问题描述

可能重复:
为什么在Java的声明中声明了wait()和notify()对象类?

我想知道为什么Object类中存在 notify() notifyAll() wait()方法,而其他线程相关方法是否存在于Java的Thread类中?

I was wondering why notify(), notifyAll() and wait() methods are present in Object class, whereas other thread related methods are present in Thread class in Java ?

推荐答案

线程可以使用对象将消息从一个线程传输到另一个线程,这些方法允许这种情况发生.线程调用wait()表示我正在等待将消息发送到此对象".另一个线程可以调用notify()说我正在向该对象发送消息".因此,对象是线程之间不显式引用彼此进行通信的管道.如果这些方法在Thread类中,则两个线程将需要相互引用才能进行通信.相反,所有通信线程只需要同意使用某些特定的共享资源即可.

Threads can use Objects to transmit messages from one thread to another, and these methods allow that to happen. A Thread calls wait() to say "I am waiting for a message to be sent to this object." Another thread can call notify() to say "I am sending a message to that object." The Object is therefore a conduit through which threads communicate without explicitly referencing each other. If the methods were in the Thread class, then two threads would need to have references to one another to communicate. Instead, all communicating threads just need to agree to use some specific shared resource.

[来自http://www.coderanch.com/how-to/java/WaitAndNotifyInObjectClass]

[from http://www.coderanch.com/how-to/java/WaitAndNotifyInObjectClass]

这篇关于Java notify(),notifyAll()和wait()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆