併發程式設計學習第一天 執行緒終止

2021-10-06 14:14:35 字數 2112 閱讀 7578

執行緒終止分為兩種:自然終止和強制終止

自然終止即執行緒自然執行完或出現異常終止。

強制終止會為暴力終止和通知性終止

暴力終止是通過呼叫stop()、resume()、suspend()等,但是在jdk1.8後已不建議使用(已過時),因為stop()會導致執行緒不會正確釋放資源,suspend()執行緒不會釋放資源,容易導致死鎖。所以才有了通知性終止。

通知性終止是通過interrupt()、isinterrupt()、static方法interrupted()實現,但是執行緒要主動處理相關狀態。

interrupt() :呼叫乙個執行緒的interrupt() 方法中斷乙個執行緒,並不是強行關閉這個執行緒,只是跟這個執行緒打個招呼,將執行緒的中斷標誌位置為true,執行緒是否中斷,由執行緒本身決定。

isinterrupted() :判定當前執行緒是否處於中斷狀態。

static方法interrupted() :判定當前執行緒是否處於中斷狀態,同時中斷標誌位改為false。

方法裡如果丟擲interruptedexception,執行緒的中斷標誌位會被復位成false,如果確實是需要中斷執行緒,要求我們自己在catch語句塊裡再次呼叫interrupt()。

一張圖來看看執行緒的生命週期及各種狀態

直接上**

public

class

endthread

system.out.

println

(threadname +

" 當前的 interrupted flag 是"

+isinterrupted()

);}}

public

static

void

main

(string[

] args)

throws interruptedexception

}

執行結果:

從結果可以看出,當主線程休眠1000毫秒時,子執行緒一直在執行,當執行到 endthread.interrupt(); 時,子執行緒判斷到isinterrupted為true則跳出while並列印出thread-0 當前的 interrupted flag 是true這句話。

如果是能通實現runnable介面的執行緒,要通過判斷thread.currentthread().isinterrupted()來實現

public

class

endthread

system.out.

println

(threadname +

" 當前的 interrupted flag 是"

+ thread.

currentthread()

.isinterrupted()

);}}

public

static

void

main

(string[

] args)

throws interruptedexception

}

如果使用中斷執行緒(interrupt)則要注意異常處理,如果報出interruptedexception異常後中斷標誌位為重置為false,所以在catch要加入interrupt(),否則執行緒全繼續執行。

private

static

class

useendthread

extends

thread

catch

(interruptedexception e)

} system.out.

println

(threadname +

" 當前的 interrupted flag 是"

+isinterrupted()

);}}

以上是get到的執行緒終止的一些知識,記錄一下備忘,希望對和我一樣的小白有所幫助!

併發程式設計第一天

synchronized修飾的地方 1.修飾物件,就是,新建乙個物件,修飾她,這樣每一次執行syschronized包裹的 塊,必須取得拿 到物件鎖然後才可以執行這個 塊 2.修飾公共的方法,這個鎖的擁有者就是thsi,就是這個類的例項 3.修飾靜態的方法,這個所得擁有者就是test.class髒讀...

學習程式設計的第一天

今天第一次使用devcpp,用這個軟體完成了一些簡單的程式設計,突然發現一扇嶄新的道路敞開在我的面前,原來以前玩的遊戲都是這樣被創造的啊!看著這些源 突然想到了當年玩魔獸爭霸的時候編輯rpg遊戲,我只會用地圖修改器創作遊戲,但是別人卻是用一長串看不懂的源 編寫,當時覺得那就像天書一樣複雜難懂,沒想到...

Linux C 程式設計學習第一天

程式基本概念 c語言是面向過程的語言,而c 是物件導向的語言。c語言的可移植性,或者稱為平台無關,該平台指作業系統 os 也可以指計算機體系結構 architecture 也可以指兩者的組合,不同的計算機體系結構有不同的指令集,可以識別的機器指令格式是不同的,直接使用彙編或者機器指令寫出來的程式,只...