關於java中的interrupt

1、概念java

java中線程有開始,運行(就緒,運行),阻塞,等待,終止這幾種狀態。其中在等待的時候能夠經過設置中斷標誌位來喚醒線程。通常狀況下等待狀態的線程檢查到中斷標誌被置位,則會拋出InterruptedException異常,捕獲異常,復位中斷標誌,能夠使線程繼續運行。
ide

thread.interrupt()  設置中斷標識位線程

Thread.interrupt() 回覆中斷標識位code

thread.isInterrupted()  返回中斷標識位get

什麼狀況下能夠使用Interrunptit

(1)若是線程在調用 Object 類的 wait()、wait(long) 或 wait(long, int) 方法,或者該類的 join()、join(long)、join(long, int)、sleep(long) 或 sleep(long, int) 方法過程當中受阻,則其中斷狀態將被清除,它還將收到一個InterruptedException異常。這個時候,咱們能夠經過捕獲InterruptedException異常來終止線程的執行,具體能夠經過return等退出或改變共享變量的值使其退出。io

(2)若是該線程在可中斷的通道上的 I/O 操做中受阻,則該通道將被關閉,該線程的中斷狀態將被設置而且該線程將收到一個 ClosedByInterruptException。這時候處理方法同樣,只是捕獲的異常不同而已。class


2、代碼thread

public static void main(String[] args) {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println(e.getStackTrace());
                System.out.println("thread is interrupt ? >>> " + Thread.currentThread().isInterrupted());
                Thread.currentThread().interrupt();
                System.out.println("thread is interrupt ? >>> " + Thread.currentThread().isInterrupted());
            }
        }
    });

    thread.start();
    try {
        TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
    }

    thread.interrupt();
}

輸出結果:變量

[Ljava.lang.StackTraceElement;@1e0c386d

thread is interrupt ? >>> false

thread is interrupt ? >>> true

相關文章
相關標籤/搜索