在java中使用Object作为互斥锁
你好,好心人,我需要一些帮助。
我正在编写一个音乐播放器,可以从网络传输音乐。如果我在音乐缓冲完成之前按下播放按钮,我希望它等待。
我尝试做这样的事情:
Object mutex = new Object();
public void main() {
startStreaming();
mutex.notify();
}
private void onClickPlayButton() {
mutex.wait();
}
问题是如果抛出“llegalMonitorStateException
”,则不会按下 mutex.notify()
的 playButton。您通常如何解决此类问题?
编辑以明确。我的问题是:如何让按钮等待“startStreamning”方法完成?
Hello there good poeple, I need some help.
I'm writing a music player which streams music from the web. If I pres the play button before the music is done buffering I want it to wait.
I tried doing something like this:
Object mutex = new Object();
public void main() {
startStreaming();
mutex.notify();
}
private void onClickPlayButton() {
mutex.wait();
}
The problem is that is the playButton is not pressed the mutex.notify()
if throws a "llegalMonitorStateException
". How do you normally solve problems like this?
EDIT To make clear. My question is: How do I make the button wait for the "startStreamning" method to finish?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
根据 JavaDoc,
为了调用
mutex.wait()
或mutex.notify()
,调用线程必须拥有对象互斥锁上的锁。此异常是如果您在没有前面的
synchronized (mutex) { }
的情况下调用它,则会抛出该异常。查看此链接中的
wait
和notify
的精美动画:等待和通知如何真正发挥作用?According to the JavaDoc,
In order to call
mutex.wait()
ormutex.notify()
, the calling thread must own a lock on object mutex.This exception is thrown if you call it without a preceding
synchronized (mutex) { }
Check out the nice animation of
wait
andnotify
in this link : How do wait and notify really work?对于 wait()、notify() 调用,您需要同步代码。试试这个:
for wait(), notify() call, you need a synchronized code. try this:
尝试使用 Semaphore 与 0初始许可。
信号量互斥体 = new Semaphore(0);
在主
mutex.release();
中点击
mutex.acquire();
Try use Semaphore with 0 initial permit.
Semaphore mutex = new Semaphore(0);
in main
mutex.release();
in on click
mutex.acquire();
来自javadoc
等待
此方法只能由该对象监视器的所有者的线程调用
以及通知
此方法只能由该对象监视器的所有者的线程调用。
这意味着在使用notify和wait时必须使用互斥体进行同步
from javadoc
wait
This method should only be called by a thread that is the owner of this object's monitor
and for notify
This method should only be called by a thread that is the owner of this object's monitor.
this means htat you have to synchronize using the mutex when using notify and wait
在
通知
之前,您必须等待
。You have to
wait
before younotify
.您必须同步互斥体才能调用通知并等待
You have to synchronize on the mutex to call notify and wait
您可以考虑使用更复杂的锁对象,或者只是在 try/catch 块中咀嚼异常。后者绝对是“又快又脏”。
有关更高级的锁定对象,请查看 http://download。 oracle.com/javase/tutorial/essential/concurrency/newlocks.html
You can either look at using more complex lock objects, or simply munch the exception in a try/catch block. The later is definitely "quick and dirty".
For a more advance locking objects, take a look at http://download.oracle.com/javase/tutorial/essential/concurrency/newlocks.html