2015年4月1日 星期三

[Android] why is my thread not stopped?

In general, the thread body will look like:
private class myThread extends Thread {
 @Override
 public void run() {
  super.run();
  Log.d(TAG,"myThread() entered...");
  while(!isInterrupted()) {
   Thread.sleep(1000);
    }
    catch (InterruptedException e) {   
     e.printStackTrace();    
    }
   }    
  }
  Log.d(TAG,"myThread() exited...");
 }
}
If we want to stop it, we can use interrupt().
For example, if we use mMyThread = new myThread() to establish the thread, we can stop it by mMyThread.interrupt().

We found that Log.d(TAG,"myThread() entered...") will be executed.
It means that mMyThread = new myThread() works normally.
However, Log.d(TAG,"myThread() exited...") is not executed.
Why? 

The reason is that the thread may be in Thread.sleep() when we call interrupt().
It will jump to catch (InterruptedException e) then and the interrupt flag will be resetted. 
When the thread runs back to while(!isInterrupted()), it is still true.

How should we fix it?
private class myThread extends Thread {
 @Override
 public void run() {
  super.run();
  Log.d(TAG,"myThread() entered...");
  while(!isInterrupted()) {
   Thread.sleep(1000);
    }
    catch (InterruptedException e) {   
     e.printStackTrace(); 
     Thread.currentThread().interrupt();
    }
   }    
  }
  Log.d(TAG,"myThread() exited...");
 }
}
Just add "Thread.currentThread().interrupt()" within "catch (InterruptedException e)".
It will set the flag interrupt again.
"Log.d(TAG,"myThread() exited...")" will be executed then.

沒有留言:

張貼留言