Thread not interrupting even though I'm calling thread.interrupt() Thread not interrupting even though I'm calling thread.interrupt() multithreading multithreading

Thread not interrupting even though I'm calling thread.interrupt()


You are calling interrupt() on the playing thread but it is probably waiting in sleep at the time. This will caught sleep to throw a InterruptedException. You need to catch that exception and exit the loop to stop the playing:

try {    Thread.sleep(NOTE_DURATION);} catch (InterruptedException e) {    // XXX need to stop playing here, maybe return or break?    return;}

Since the interrupt() can also come at a different time, you need to test for interrupt status and quit your loop:

if (!paused && !Thread.currentThread().isInterrupted()) {   ...

Also, all variables that are shared between two threads either need to be synchronized or be marked volatile. The paused flag should probably be volatile here:

volatile boolean paused = false

Lastly, for posterity, when you catch InterruptedException, it clears the interrupt status of the thread. It is usually good practice to immediately set the interrupt flag on the thread so others can test for it:

try {    Thread.sleep(NOTE_DURATION);} catch (InterruptedException e) {    // re-establish the interrupt condition    Thread.currentThread.interrupt();    ...}