Thread.interrupt()的理解

目標(biāo)

一個線程不應(yīng)該由其他線程來強(qiáng)制中斷或停止,而是應(yīng)該由線程自己自行停止。
Thread.interrupt 的作用其實(shí)也不是中斷線程,而是「通知線程應(yīng)該中斷」

代碼

package com.zoterap.javabasic.current;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static java.lang.String.format;
import static java.util.concurrent.TimeUnit.SECONDS;

public class ThreadInterruptDemo {

    public static String getCurrentTime() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS"));
    }
    
    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(format("current i[%d], dateTime[%s]", i, getCurrentTime()));

                try {
                    SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    System.out.println("EXCEPTION:" + e.getMessage());
                    Thread.currentThread().interrupt();
                }

            }
        });

        /**
         * 開啟線程
         */
        t.start();

        /**
         * 主線程休眠5秒
         */
        try {
            SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        /**
         * 打印線程,嘗試中斷
         */
        t.interrupt();

    }

}

結(jié)果

current i[0], dateTime[2019-02-13 21:24:33 988]
current i[1], dateTime[2019-02-13 21:24:35 011]
current i[2], dateTime[2019-02-13 21:24:36 015]
current i[3], dateTime[2019-02-13 21:24:37 020]
current i[4], dateTime[2019-02-13 21:24:38 022]
EXCEPTION:sleep interrupted
current i[5], dateTime[2019-02-13 21:24:38 963]
EXCEPTION:sleep interrupted
current i[6], dateTime[2019-02-13 21:24:38 964]
EXCEPTION:sleep interrupted
current i[7], dateTime[2019-02-13 21:24:38 964]
EXCEPTION:sleep interrupted
current i[8], dateTime[2019-02-13 21:24:38 964]
EXCEPTION:sleep interrupted
current i[9], dateTime[2019-02-13 21:24:38 965]
EXCEPTION:sleep interrupted
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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