Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Object as a mutex in java

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?

like image 223
Martin Hansen Avatar asked May 19 '11 18:05

Martin Hansen


1 Answers

According to the JavaDoc,

IllegalMonitorStateException is thrown "to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor."

In order to call mutex.wait() or mutex.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 and notify in this link : How do wait and notify really work?

like image 93
Saurabh Gokhale Avatar answered Oct 01 '22 18:10

Saurabh Gokhale