Android中 onDestroy 方法中调用thread.interrupt() 线程不中止
猜你写的会是这样(加了sleep延时)
while (!Thread.currentThread().isInterrupted()) {
n++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//TODO:周期事件
}
不起作用?
解决方法:上部分代码加一句Thread.currentThread().interrupt()
while (!Thread.currentThread().isInterrupted()) {
n++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
//TODO:周期事件
}
由于sleep()方法中调用了interrupted(),源码如下:
if (millis == 0 && nanos == 0) {
// ...but we still have to handle being interrupted.
if (Thread.interrupted()) {
throw new InterruptedException();
}
return;
}
而interrupted()会重置中断标志,源码中解释如下:
/**
* Tests whether the current thread has been interrupted. The
* <i>interrupted status</i> of the thread is cleared by this method. In
* other words, if this method were to be called twice in succession, the
* second call would return false (unless the current thread were
* interrupted again, after the first call had cleared its interrupted
* status and before the second call had examined it).
*
* <p>A thread interruption ignored because a thread was not alive
* at the time of the interrupt will be reflected by this method
* returning false.
*
* @return <code>true</code> if the current thread has been interrupted;
* <code>false</code> otherwise.
* @see #isInterrupted()
* @revised 6.0
*/
翻译:
测试当前线程是否已被中断。 通过此方法可以清除线程的中断状态。 换句话说,如果要连续调用此方法两次,则第二次调用将返回false(除非当前线程在第一次调用清除其中断状态之后且在第二次调用检查其状态之前再次中断)。