I have a class that plays background music on infinite loop for a game. I want it to stop when another class calls the stopPlaying() method on the BackgroundMusic object. According to Oracle docs, there is no way to stop a thread in Java.
It said to use a variable that it checks and stops when the variable is a certain value. I tried making a boolean running that gets set to false when I call stopPlaying() and tried making the while loop have running as the condition instead of true, but that did not work without a delay. (Message edited from before)
I would put my class in here, but this site keeps saying it's not formatted properly, and I've done this before (pasting from Eclipse). I put it on PasteBin: http://pastebin.com/edCH2DXE
It's kind of a big hammer, but you can interrupt the thread by calling musicThread.interrupt(). This will cause isInterrupted() to return true for the music thread. If the thread was doing some blocking I/O at the time, this might cause InterruptedException to be thrown, so you need to catch that as well:
try {
while (!Thread.currentThread().isInterrupted()) {
// play music
}
} catch (InterruptedException ex) {
// any cleanup necessary
}
Again, it's a big hammer, and it's better to use the boolean flag approach if you can.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With