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...");
}
}
如果你想要停止這個thread,我們可用interrupt()的方法,
例如,mMyThread = new myThread()是用來建立,
那mMyThread.interrupt()就是用來停止它,
可是我們發現Log.d(TAG,"myThread() entered...")會被執行,
表示mMyThread = new myThread()沒問題,
但是Log.d(TAG,"myThread() exited...")怎麼都沒被呼叫呢?
明明我們有呼叫mMyThread.interrupt()啊...
原來,thread可能在Thread.sleep()裡,
你呼叫interrupt()時,Thread會跑到catch (InterruptedException e),
但此時呢,interrupt會被reset,
所以回到while(!isInterrupted()),它還是成立,
那麼,我們該如何做呢,
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...");
}
}
只要在"catch (InterruptedException e)"加上"Thread.currentThread().interrupt()"即可,再設一次interrupt,
此時"Log.d(TAG,"myThread() exited...")"就會被執行到了
沒有留言:
張貼留言