Search code examples
javamultithreadingif-statementwhile-loopbackground-music

if statement not called unless condition is printed before


Ok, this is an odd one. Basically I am creating a playlist of sorts so background music in my game will play after the previous song as finished, etc. If I remove the System.out.println(music.isPlaying()); then the block of code within the if statement never gets called, even when music.isPlaying() is in fact false . But if I add the print statement before it, then magically it works as it should. But this is only with the print statement, I can't just send the boolean to some empty method or set a boolean variable to it, it only works when sent to the console. However, for obvious reasons, I would not like it's truth value to be spammed to the console. Does anyone know why this is acting out this way and how I could fix it?

    while (true) {
        System.out.println(music.isPlaying()); // Only works with this here
        if (!music.isPlaying()) {
            System.out.println("Changing song");
            currentSongIndex++;
            if (currentSongIndex >= musicFiles.size())
                currentSongIndex = 0;
            music = musicFiles.get(currentSongIndex);
            music.play();
        }
    }

I'm not sure if this has any affect on this but this loop is being called on a 2nd thread, as my game is ran on it's own thread. If for any reason this might be the reason, let me know and I can post my multi-threading code.


Solution

  • You need to declare the boolean variable that Music.isPlaying() is using as a volatile like this:

    volatile boolean playing;
    

    You can read more about what the volatile keyword does on Javamex.