多線程中的Interrupt、Interrupted、IsInterrupted 的區分

1. Interrupt是指對該線程設置了終止狀態, 並沒有終止該線程。


2. Interrupted是指判斷當前線程是否終止了, 並且會由於interrupt設置的線程終止狀態。

public class MyThread extends Thread {
	private int count;
	public void run() {
		for (int i = 0; i < 100000; i++) {
			count ++;
		}
	}
}

public class TestMain {
	public static void main(String[] args) throws InterruptedException {
		MyThread mt = new MyThread();
		mt.start();
		mt.interrupt();
		System.out.println(mt.interrupted()); // 當前線程是否中斷狀態  false
		System.out.println(mt.interrupted());// 當前線程是否中斷狀態  false
		

	}
}
public class TestInterrupted {
	public static void main(String[] args) {
		Thread.currentThread().interrupt();  // 此時設置爲中斷狀態
		System.out.println(Thread.interrupted()); // 此時中斷狀態爲True 但是 此方法清除了中斷狀態
		System.out.println(Thread.interrupted()); // 此時中斷狀態爲False
	}
}



3. IsInterruped是指判斷線程Thread對象是否已經是終止狀態,但並不清除狀態。


public class IsInterrupted {
	public static void main(String[] args) {
		MyThread mt = new MyThread();
		mt.start();
		mt.interrupt();
		System.out.println(mt.isInterrupted()); // 判斷測試線程是否處於中斷狀態  並且不清除狀態標識
		System.out.println(mt.isInterrupted()); // 判斷測試線程Thread對象是否已經是中斷狀態 但不清除狀態標識.
	}
}

沒懂的朋友聯繫我 wangyan199366 (wechat)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章