2019-04-01

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;

}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容