Pergunta

I am working on a program that plays music in the background via multithreading, because the GUI freezes up otherwise. I have a basic knowledge of multithreading (volatile, synchronizing, etc.) but I was wondering how to immediately stop/pause a thread (even when processes are processing). I have the music looping in the background but if I hook a stop variable up to the loop the song has to stop playing for the music to stop. So my question remains, from the parent thread is there any way to immediately pause or terminate the music in the middle of the song, because I have audio to play after it.

Foi útil?

Solução

First, most loops in a thread should look similar to this:

while(!isInterrupted()) {
    try {
       // do something (like play song)
    } catch (InterruptedException e) {
        interrupt();
    }
}

If there are blocking calls inside the loop (which it sounds like from your description), they likely allow interrupt(). A call to interrupt() from the outside of the thread will break the blocking call and dump you into the catch block. This ends up clearing the "interrupt" flag, so you need to call interrupt again to get out of the loop.

Depending on how you're playing music:

  • If you're using a library that has a "pause" or "stop" method to play the music, you can just use that. Looks like you're using jFugue - its player has a pause() method - have you tried calling that?
  • If you're doing something else, you'll need to keep track of the song's position and call interrupt() on the thread. If you want to restart, you'll need to seek back to the tracked position

Note that if you want to restart with the above loop, you'll need a nested loop such as:

while(true) {
    while(!isInterrupted()) {
        ...
    }
}

If you only have the !isInterrupted() loop, the thread will finish, and cannot be restarted.

Hope this helps!

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top