不同執行緒間的等待喚醒機制

2021-09-29 10:23:22 字數 1161 閱讀 6999

具體來說是執行緒間的通訊問題;

表示為:student 資源;setthread 生產線程以及getthread 消費執行緒。

void wait ()執行緒等待

void notify()喚醒等待的單個執行緒;

生產線程生產好資源後,通知消費執行緒消費,與此同時再次和消費爭搶時間片,但是此時標記為true,表示有資源,就會等待,並釋放鎖;從而讓消費執行緒消費;依次迴圈

public

class

mytest

}class

student

class

setthread

extends

thread

//生產線程:當我生產出乙個資源時,等待著,並通知消費者消費

@override

public

void

run(

)catch

(interruptedexception e)}if

(i %2==

0)else

//有資源了,通知消費者去消費

student.flag=

true

;//修改標記

student.

notify()

;//喚醒消費執行緒,通知後,兩個再次搶占時間片

} i++;}

}}class

getthread

extends

thread

//消費執行緒:消費了資源,等待著,並通知生產者去生產

@override

public

void

run(

)catch

(interruptedexception e)

}//消費

system.out.

println

(student.name +

"==="

+ student.age)

;//通知

student.flag=

false

;//修改標記

student.

notify()

;//通知生產者生產,兩個執行緒再次爭搶時間片}}

}}

執行緒間通訊 等待喚醒機制

執行緒間通訊 其實就是多個執行緒在操作同乙個資源,但是操作的動作不同 class res2 class input2 implements runnable public void run catch interruptedexception e if x 0 else x x 1 2 r.flag...

執行緒間的通訊 等待喚醒機制

執行緒間的通訊 同步執行緒必須滿足兩個條件 一 兩個或兩個以上的執行緒 二 都使用同乙個鎖物件 題目描述 首先有乙個資源池 resource 輸入執行緒 input 不斷往資源池內新增內容,輸出執行緒 output 不斷往外輸出內容 並且兩個執行緒需要同步。需要的結果是,輸入執行緒輸入乙個內容,然後...

執行緒間的等待喚醒機制 (一)

wait 可以是當前執行緒進行等待 notify 喚醒操作的執行緒 notifyall 喚醒所有執行緒。當前執行緒必須擁有此物件監視器。該執行緒發布對此監視器的所有權並等待,直到其他執行緒通過呼叫 notify 方法,或 notifyall 方法通知在此物件的監視器上等待的執行緒醒來。然後該執行緒將...