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

前端 未结 1 1309
生来不讨喜
生来不讨喜 2020-12-03 22:53

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

相关标签:
1条回答
  • 2020-12-03 23:34

    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();
        ...
    }
    
    0 讨论(0)
提交回复
热议问题