I'm trying to get better acquainted with threaded programming by building a mock music player. It's not going over so well
What am I doing wrong in the code snipped below? The snippet below is inside the run() method of the MusicPlayer class.
It seems that it simply doesn't excute as intended. The behavior I want is:
- When in Off mode: do nothing
- When in Playing mode: Wait until song finishes, then remove song from playlist (call PlaySong)
- When in Pause mode: Wait (pauseTimeOut) milliseconds, and if nothing happens, go to Off mode.
The thread runs fine, but it seems that it waits forever in whatever state it is in.
I apologize for the weird if statements..
Code:
while (alive) {
System.out.println("State: "+state);
switch (state) {
case Off:
System.out.println("System is off");
try { cond.await(); }
catch(InterruptedException e) { alive = false; }
break;
case Paused:
boolean stillWaiting=true;
System.out.println("Waiting..");
try { stillWaiting=cond.await(pauseTimeOut, TimeUnit.MILLISECONDS); }
catch(InterruptedException e) { alive = false; }
if(stillWaiting) {
//Do nothing
} else if (state == States.Paused) {
state=States.Off;
}
break;
case Playing:
System.out.println("Playing..");
if(playlist == 0) {
state = States.Paused;
} else {
boolean waitingEndSong=true;
try { waitingEndSong=cond.await(songTime, TimeUnit.MILLISECONDS); }
catch(InterruptedException e) { alive = false; }
if(waitingEndSong) {
//Do nothing
} else if (state == States.Playing) {
PlaySong();
}
break;
}
try { cond.await(); }
catch(InterruptedException e) { alive = false; }
break;
default:
alive = false;
}
}