编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

Java notify(),notifyAll()和wait()方法:Java notify(), notifyAll() and wait() methods

muca 线程 2022-5-13 10:44 72人围观

腾讯云服务器
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()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^