本文介绍了是Java wait(),notify()的实现显着不同于锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于好奇,当Java实现wait()和notify()方法,他们真的只是使用锁?即wait()获取一个互斥,notify()释放一个互斥,notifyAll()释放所有互斥(当然在同一个对象中)?

Out of curiosity, when Java implements wait() and notify() methods, are they really just using locks? i.e., wait() acquires a mutex, notify() release a mutex, notifyAll() releases all mutexes (in the same object, of course)?

除了比使用锁更麻烦,使用wait()和notify()还有其他优点吗?

Other than being less cumbersome than using locks, are there other advantages of using wait() and notify()?

我意识到自己在Brian的评论之后感到困惑:

I realized what I confused myself about after Brian's comments:

它释放锁并将其传递给正在等待互斥体的synchronized语句的其他人,然后等待具有锁的其他人通知并调用notify,这将锁传递给调用wait的原始线程。我认为这是你困惑的地方。 - Brian 17分钟前

wait doesn't lock, it releases the lock and passes it to someone else who's waiting on a synchronized statement for the mutex, then waits to be notified by someone else who has the lock and calls notify, which passes the lock back to the original thread that called wait. I think that's where you're getting confused. – Brian 17 mins ago

推荐答案

wait() notify()不要进行任何监视器采集。作为这些方法的javadoc状态,调用者必须在调用之前已经获取了监视器。事实上, wait()实际上释放呼叫者获取的监视器(虽然,我想技术上等待 (re)采集,最终返回之前)。

wait() and notify() don't do any monitor acquisition. as the javadoc for these methods state, the caller must have acquired the monitor before calling. in fact, wait() actually releases the monitor the caller acquired (although, i guess technically wait does do monitor (re)acquisition before finally returning).

这篇关于是Java wait(),notify()的实现显着不同于锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 04:00