優(yōu)雅的中斷線程

創(chuàng)建線程的兩種方法:

  • 繼承Thread, 并實(shí)現(xiàn)run方法;
  • 實(shí)現(xiàn)Runnable;

不管是使用哪一種方法創(chuàng)建線程,run方法的任務(wù)執(zhí)行完了,線程就自動(dòng)停止.
stop():不建議使用

public class ThreadStop extends Thread {
    @Override
    public void run() {
        super.run();
        for (int i=0;i<100000;i++){
            Log.e("ThreadStop","run: "+i);
        }
    }
}

thread = new ThreadStop();
        thread.start();
        thread.stop();
運(yùn)行的日志

雖然stop()可以停止一個(gè)線程,但是這個(gè)方法是不安全的,因?yàn)槿绻€程中操作的是一些復(fù)雜一點(diǎn)的對(duì)象,例如bitmap, 線程突然停止的話就會(huì)發(fā)生一些意想不到的bug, 而且這個(gè)api已經(jīng)被JAVA棄用作廢了,最好不要使用它。

isInterrupted():

測(cè)試線程Thread對(duì)象是否已經(jīng)是中斷狀態(tài),但是不清除狀態(tài)標(biāo)志。

interrupted():

內(nèi)部實(shí)現(xiàn)是調(diào)用的當(dāng)前線程的isInterrupted(),并且會(huì)重置當(dāng)前線程的中斷狀態(tài),(取反,如果連續(xù)調(diào)用兩次該方法,則第二次調(diào)用將返回 false (在第一次調(diào)用線程中斷被忽略,因?yàn)樵谥袛鄷r(shí)不處于活動(dòng)狀態(tài)的線程將由此返回 false 的方法反映出來(lái)))

interrupt():建議使用

interrupt是中斷的意思,調(diào)用interrupt()方法僅僅是在當(dāng)前線程中打了一個(gè)停止的標(biāo)記,并不是真正停止線程;

 Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i ++){
                    try {
                        Thread.sleep(100);
                        Log.e("interrupt","thread run" + i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;
                    }
                }
            }
        });
        thread.start();
        Log.e("interrupt","thread sleep" + "");
        try {
            Thread.sleep(500);
        } catch (InterruptedException e){
            e.printStackTrace();
        }
        thread.interrupt();
        Log.e("interrupt","thread end");

09-28 17:14:54.234 2210-2210/com.example.administrator.javademo E/interrupt: thread sleep
09-28 17:14:54.334 2210-2323/com.example.administrator.javademo E/interrupt: thread run0
09-28 17:14:54.434 2210-2323/com.example.administrator.javademo E/interrupt: thread run1
09-28 17:14:54.534 2210-2323/com.example.administrator.javademo E/interrupt: thread run2
09-28 17:14:54.644 2210-2323/com.example.administrator.javademo E/interrupt: thread run3
09-28 17:14:54.734 2210-2210/com.example.administrator.javademo E/interrupt: thread end
09-28 17:14:54.734 2210-2323/com.example.administrator.javademo W/System.err: java.lang.InterruptedException

安全終止線程, 可以再加多一個(gè)判斷, 使用 this.interrupted() 來(lái)判斷當(dāng)前線程是否停止了 ,如果停止就不往下執(zhí)行 ,直接跳出循環(huán)體;

if (this.interrupted()){
     break;
}

或者:

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

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

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