多線程學習-day-02理解中斷

線程基礎、線程之間的共享和協作

(目前會將一些概念簡單描述,一些重點的點會詳細描述)

上一章回顧:

基礎概念:

1,CPU核心數,線程數

2,CPU時間片輪轉機制

3,什麼是進程和線程

4,什麼是並行和併發

5,高併發的意義、好處和注意事項

線程基礎:

1,啓動和終止線程

        ①、三種啓動線程方式

 

本章學習目標:

理解中斷

如何安全的終止線程

 

1,理解中斷

        線程自然終止:自然執行完 或 拋出未處理異常

        stop()、resume()、suspend() 三個方法已經在後續的jdk版本已過時,不建議使用

        stop()方法:會導致線程不正確釋放資源;

        suspend()方法:掛起,容易導致死鎖

        Java線程是協作式工作,而非搶佔式工作;

        介紹三種中斷方式:

        ①、interrupt()方法

                interrupt()方法中斷一個線程,並不是強制關閉該線程,只是跟該線程打個招呼,將線程的中斷標誌位置爲true,線程是否中斷,由線程本身決定;

        ②、inInterrupted()方法

                inInterrupted()方法判斷當前線程是否處於中斷狀態;

        ③、static 方法interrupted()方法

                static方法interrupted()方法判斷當前線程是否處於中斷狀態,並將中斷標誌位改爲false;

        注:方法裏如果拋出InterruptedException,線程的中斷標誌位會被置爲false,如果確實需要中斷線程,則需要在catch裏面再次調用interrupt()方法

public class HasInterruptException {

	// 定義一個私有的Thread集成類
	private static class UseThread extends Thread {

		@Override
		public void run() {
			// 獲取當前線程名字
			String threadName = Thread.currentThread().getName();
			// 判斷線程是否處於中斷標誌位
			while (!isInterrupted()) {
				// 測試用interrupt中斷後,報InterruptedException時狀態變化
				try {
					System.out.println(threadName + "is run !!!!");
					// 設置休眠毫秒數
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// 判斷中斷後拋出InterruptedException後中斷標誌位的狀態
					System.out.println(threadName + " interrupt flag is " + isInterrupted());
					// 如果拋出InterruptedException後中斷標誌位置爲了false,則需要手動再調用interrupt()方法,如果不調用,則中斷標誌位爲false,則會一直在死循環中而不會退出
					interrupt();
					e.printStackTrace();
				}
				// 打印出線程名稱
				System.out.println(threadName);
			}
			// 查看當前線程中斷標誌位的狀態
			System.out.println(threadName + " interrupt flag is " + isInterrupted());
		}
	}

	public static void main(String[] args) throws InterruptedException {
		UseThread useThread = new UseThread();
		useThread.setName("HasInterruptException--");
		useThread.start();
		Thread.sleep(800);
		useThread.interrupt();
	}
}

控制檯輸出結果:
HasInterruptException--is run !!!!
HasInterruptException-- interrupt flag is false
java.lang.InterruptedException: sleep interrupted
HasInterruptException--
HasInterruptException-- interrupt flag is true
	at java.lang.Thread.sleep(Native Method)
	at com.xiangxue.ch1.safeend.HasInterruptException$UseThread.run(HasInterruptException.java:18)

來自享學IT教育課後總結。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章