Thread 停止的方式
線程停止的3種方式:
第一種方式:interrupt()
interrupted();調(diào)用此方法僅僅是在當(dāng)前線程中打一個停止的標(biāo)記,并不是正在的停止線程
判斷當(dāng)前線程是否停止?fàn)顟B(tài):
[if !supportLists]1、[endif]this.interrupted() 靜態(tài)方法,測試當(dāng)前線程是否已經(jīng)是中斷狀態(tài),執(zhí)行后具有將狀態(tài)標(biāo)志清除為false的功能
[if !supportLists]2、[endif]this.isInterrupted() 普通public方法,測試線程Thread對象是否已經(jīng)中斷狀態(tài),但不清除標(biāo)志。
第二種方式:異常法
private
class ExceptionThread extends Thread {
? ? @Override
? ? public void run() {
? ? ? ? super.run();
? ? ? ? try {
? ? ? ? ? ? for (inti = 0; i < Integer.MAX_VALUE; i++){
? ? ? ? ? ? ? ? Log.e("ExceptionThread", "i: " + i);
? ? ? ? ? ? ? ? if (this.isInterrupted()) {
??????????????????? Log.e("ExceptionThread", "已經(jīng)停止了......");
? ? ? ? ? ? ? ? throw new InterruptedException();
??????????????? }
??????????????? Log.e("ExceptionThread", "我在for循環(huán)下面");
??????????? }
??????? } catch (InterruptedException e) {
??????????? Log.e("InterruptedException", "我在 catch InterruptedException");
??????????? e.printStackTrace();
??????? }
??? }
}
第三種方式:return
While(true) {
If (thread.isInterrupted()) {
???return;
}
}