为什么在Java的Object类中声明了wait()和notify()? [英] Why are wait() and notify() declared in Java's Object class?

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

问题描述

为什么在对象中声明的 wait() notify()方法 class,而不是 Thread 类?

推荐答案

因为,你等待一个给定的对象(或者特别是它的监视器)来使用这个功能。

Because, you wait on a given Object (or specifically, its monitor) to use this functionality.

我认为你可能会误解这些方法是如何工作的。它们不仅仅处于线程粒度级别,即只是调用 wait()并被其唤醒下次调用 notify()。相反,你总是在特定对象上调用 wait(),并且只会通过调用 notify 关于那个对象。

I think you may be mistaken on how these methods work. They're not simply at a Thread-granularity level, i.e. it is not a case of just calling wait() and being woken up by the next call to notify(). Rather, you always call wait() on a specific object, and will only be woken by calls to notify on that object.

这很好,因为否则并发原语就不会扩展;它等同于拥有全局命名空间,因为在程序中的任何地方对 notify()的任何调用都有可能弄乱任何并发代码因为他们会在 wait()调用时唤醒任何阻塞的线程。因此你在特定对象上调用它们的原因;它为wait-notify对提供了一个上下文,所以当你在一个私有对象上调用 myBlockingObject.notify()时,你可以确定你会只唤醒在您的类中调用wait方法的线程。一些可能在另一个对象上等待的Spring线程将不会被此调用唤醒,反之亦然。

This is good because otherwise concurrency primitives just wouldn't scale; it would be equivalent to having global namespaces, since any calls to notify() anywhere in your program would have the potential to mess up any concurrent code as they would wake up any threads blocking on a wait() call. Hence the reason that you call them on a specific object; it gives a context for the wait-notify pair to operate on, so when you call myBlockingObject.notify(), on a private object, you can be sure that you'll only wake up threads that called wait methods in your class. Some Spring thread that might be waiting on another object will not be woken up by this call, and vice versa.

编辑:或从另一个角度解决它 - 我期待根据你的问题,你认为你会得到一个等待线程的句柄,并在那个线程上调用 notify()来唤醒它。不这样做的原因是你必须自己做很多家务。要等待的线程必须在其他线程可以看到的地方发布对自己的引用;这必须正确同步以强制一致性和可见性。当你想要唤醒一个线程时,你必须抓住这个引用,唤醒它,并从你读取它的任何地方删除它。与在睡眠中调用 myObj.wait()相比,涉及更多的手动脚手架,并且更多的机会出错(特别是在并发环境中)线程,然后在waker线程中 myObj.notify()

Or to address it from another perspective - I expect from your question you thought you would get a handle to the waiting thread and call notify() on that Thread to wake it up. The reason it's not done this way, is that you would have to do a lot of housekeeping yourself. The thread going to wait would have to publish a reference to itself somewhere that other threads could see it; this would have to be properly synchronized to enforce consistency and visibility. And when you want to wake up a thread you'd have to get hold of this reference, awaken it, and remove it from wherever you read it from. There's a lot more manual scaffolding involved, and a lot more chance of going wrong with it (especially in a concurrent environment) compared to just calling myObj.wait() in the sleeping thread and then myObj.notify() in the waker thread.

这篇关于为什么在Java的Object类中声明了wait()和notify()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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