執行緒狀態及切換(三)

2021-09-28 16:55:04 字數 2782 閱讀 9969

主要是實現執行緒各種執行狀態

執行緒5中執行狀態:

new建立完執行緒後執行緒狀態為new

runnable r =

newrunnable()

catch

(interruptedexception e)}}

; thread thread =

newthread

(r,"執行緒1");

system.out.

println

("新建:"

+thread.

getstate()

);//新建:new

執行緒執行start()

thread.

start()

; system.out.

println

("開始執行:"

+thread.

getstate()

);//開始執行:runnable

讓執行緒計時等待 thread.sleep(時間);

public

static

void

main

(string[

] args)

throws interruptedexception

catch

(interruptedexception e)}}

; thread thread =

newthread

(r,"執行緒1");

system.out.

println

("新建:"

+thread.

getstate()

);thread.

start()

; system.out.

println

("開始執行:"

+thread.

getstate()

);int i=20;

while

(i>0)

檢視讓面 當執行緒執行完以後執行緒結束

我們寫乙個執行緒阻塞程式:讓執行緒爭搶資源不放導致阻塞

private

static

final object r1 =

newobject()

;private

static

final object r2 =

newobject()

;public

static

void

main

(string[

] args)

throws interruptedexception

catch

(interruptedexception e)

system.out.

println

(thread.

currentthread()

+"waiting r2");

synchronized

(r2)}}

,"執行緒1");

thread t2 =

newthread((

)->

catch

(interruptedexception e)

system.out.

println

(thread.

currentthread()

+"waiting r1");

synchronized

(r1)}}

,"執行緒2");

t1.start()

; t2.

start()

;int i=20;

while

(i>0)

}

如圖:

執行緒等待需要喚醒

public

class

mywait

for(

int i =

0; i <

5; i++

) preisa =

true

;notifyall()

;}catch

(interruptedexception e)

}synchronized

void

backb()

for(

int i =

0; i <

5; i++

) preisa =

false

;notifyall()

;}catch

(interruptedexception e)

}public

static

void

main

(string[

] args)

throws interruptedexception })

; thread b =

newthread((

)-> mywait.

backb()

);a.

start()

; b.

start()

;}}}

Java執行緒的狀態及切換

引言,前段時間面試了一波,這個問題常被問到,自己腦子裡面的知識體系比較混亂,回答的不太好,廢話不多說,直接來總結 一共有六種狀態 分別是初始狀態,就緒狀態,執行中狀態,阻塞狀態,等待狀態,超時狀態,終止狀態。初始 new 新建立的執行緒物件,此時還沒有呼叫start 方法。就緒狀態 ready 1....

java多執行緒狀態切換

一.執行緒狀態型別 1.新建狀態 new 新建立了乙個執行緒物件。2.就緒狀態 runnable 執行緒物件建立後,其他執行緒呼叫了該物件的start 方法。該狀態的執行緒位於可執行執行緒池中,變得可執行,等待獲取cpu的使用權。3.執行狀態 running 就緒狀態的執行緒獲取了cpu,執行程式 ...

執行緒狀態及常用方法

建立 就緒 執行 阻塞 結束 建立 當使用new建立新的執行緒時,處於建立狀態 就緒 呼叫start方法後,執行緒並不是立即處於執行狀態,而是出於就緒態 執行 當執行緒被分配cpu後,執行run方法後才處於執行狀態 阻塞 執行緒因為某些原因讓出cpu使用權,直到重新進入執行態 如呼叫sleep方 法...