執行緒的 6 個狀態(生命週期)

2021-09-28 23:19:48 字數 1604 閱讀 8415

面試問題

新建new、可執行runnable、已終止terminated

**演示

/**

* 展示執行緒的new、runnable、terminated狀態。即使是正在執行,也是runnable狀態,而不是running。

*/public

class

newrunnableterminated

implements

runnable

catch

(interruptedexception e)

//列印出runnable的狀態,即使是正在執行,也是runnable,而不是running

system

.out.

println

(thread.

getstate()

);trycatch

(interruptedexception e)

//列印出terminated狀態

system

.out.

println

(thread.

getstate()

);}@override

public

void

run()}

}

被阻塞blocked、等待waiting、計時等待timed waiting

**演示

/**

* 展示blocked, waiting, timedwaiting

*/public

class

blockedwaitingtimedwaiting

implements

runnable

catch

(interruptedexception e)

//列印出timed_waiting狀態,因為正在執行thread.sleep(1000);

system

.out.

println

(thread1.

getstate()

);//列印出blocked狀態,因為thread2想拿得到sync()的鎖卻拿不到

system

.out.

println

(thread2.

getstate()

);trycatch

(interruptedexception e)

//列印出waiting狀態,因為執行了wait()

system

.out.

println

(thread1.

getstate()

);}@override

public

void

run(

)private

synchronized

void

syn(

)catch

(interruptedexception e)

}}

先講上面狀態間的轉化圖示圓圈中的狀態名,再講講轉換路徑(例如new只能跳轉到runnable),最後講講轉移條件。

執行緒的生命週期狀態

第一步 新建狀態 使用new關鍵字新建執行緒,此時處於新建狀態 第二步 就緒狀態 當呼叫了該執行緒的start 方法,執行緒啟動,處於就緒狀態,但是不一定執行 第三步 執行狀態 需要考作業系統cup的排程執行,如果作業系統是搶占式排程,當執行緒搶占到了cup的執行許可權,執行緒開始執行 如果是分時排...

執行緒生命週期及狀態

示例2 多執行緒執行狀態切換示例 public class demo2 system.out.println 沒呼叫start方法,thread1當前狀態 thread1.getstate tostring thread1.start thread.sleep 2000l 等待thread1執行結束...

執行緒的狀態和生命週期

1 新建狀態 create 建立乙個執行緒類的物件後,產生的新執行緒就進入新建狀態。如 thread myth new mythread 2 可執行狀態 runable 也叫就緒狀態,呼叫start 方法後進入。3 執行狀態 running 當處於就緒狀態的執行緒被呼叫並獲得了cpu等執行必須的資源...