Thread Not Interrupting Even Though I'm Calling Thread.interrupt()
I'm learning how to use threads in Android, and to do that I've made a small application that plays a series of notes. The idea is that there is a start button and an end button an
Solution 1:
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:
volatilebooleanpaused=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();
...
}
Post a Comment for "Thread Not Interrupting Even Though I'm Calling Thread.interrupt()"