1 3併發程式設計之多執行緒通訊

2021-09-24 02:15:41 字數 2792 閱讀 3928

多執行緒之間通訊,其實就是多個執行緒在操作同乙個資源,但是操作的動作不同。

1.因為涉及到物件鎖,他們必須都放在synchronized中來使用. wait、notify一定要在synchronized裡面進行使用。

2.wait必須暫定當前正在執行的執行緒,並釋放資源鎖,讓其他執行緒可以有機會執行

3. notify/notifyall: 喚醒因鎖池中的執行緒,使之執行

是同乙個鎖的資源

案例:第乙個執行緒寫入(input)使用者,另乙個執行緒取讀取(out)使用者.實現讀乙個,寫乙個操作。

**:classres

class

intthrad

extends

thread

@override

public

void

run()

catch

(exception e)

} if

(count

== 0)

else

count

= (count

+ 1) % 2;

res.flag

= true;

// 喚醒當前執行緒

res.notify(); }

} }}

class

outthread

extends

thread

@override

public

void

run()

catch

(exception e)

}system.

out.println(

res.

username

+ "--"

+ res

.user***);

res.

flag

= false;

res.notify(); }

} }}

public

class

threacommun }

對於sleep()方法,我們首先要知道該方法是屬於thread類中的。而wait()方法,則是屬於object類中的。

sleep()方法導致了程式暫停執行指定的時間,讓出cpu該其他執行緒,但是他的監控狀態依然保持者,當指定的時間到了又會自動恢復執行狀態。

在呼叫sleep()方法的過程中,執行緒不會釋放物件鎖。

而當呼叫wait()方法的時候,執行緒會放棄物件鎖,進入等待此物件的等待鎖定池,只有針對此物件呼叫notify()方法後本執行緒才進入物件鎖定池準備

獲取物件鎖進入執行狀態。

lock 介面提供了與 synchronized 關鍵字類似的同步功能,但需要在使用時手動獲取鎖和釋放鎖。

locklock

=new

reentrantlock();

lock

.lock

();

try

finally

lock 介面可以嘗試非阻塞地獲取鎖 當前執行緒嘗試獲取鎖。如果這一時刻鎖沒有被其他執行緒獲取到,則成功獲取並持有鎖。

lock 介面能被中斷地獲取鎖 與 synchronized 不同,獲取到鎖的執行緒能夠響應中斷,當獲取到的鎖的執行緒被中斷時,中斷異常將會被丟擲,同時鎖會被釋放。

lock 介面在指定的截止時間之前獲取鎖,如果截止時間到了依舊無法獲取鎖,則返回。

condition的功能類似於在傳統的執行緒技術中的,object.wait()和object.notify()的功能。

**:class

res

class

inputthread

extends

thread

@override

public

void

run()

catch

(exception e)

} if

(count

== 0)

else

count

= (count

+ 1) % 2;

res.flag

= true;

newcondition

.signal(); }

catch

(exception e)

finally }

// } }

}class

outthrad

extends

thread

@override

public

void

run()

catch

(exception e)

}system.

out.println(

res.

username

+ ","

+ res

.***);

res.

flag

= false;

newcondition

.signal(); }

catch

(exception e)

finally //

} }

} }

public

class

threaddemo01 }

三 併發程式設計之多執行緒間通訊

1 wait notify方法 1.1 wait notify必須在synchronized中進行使用 public class respublic class inthread extends thread override public void run catch interruptedexc...

python併發程式設計之多執行緒

程序包含了執行該程式所需要所有資源 程序是乙個資源單位 執行緒是cpu的最小執行單位 每乙個程序一旦被建立 就預設開啟了一條執行緒 稱之為主線程 使用執行緒可以提高程式效率 為何不用多程序提高效率 是因為程序對作業系統的資源耗費非常高 執行緒共享建立它的程序的位址空間 程序有自己的位址空間。執行緒可...

併發程式設計專題之多執行緒之間實現通訊

多執行緒之間通訊,其實就是多個執行緒在操作同乙個資源,但是操作的動作不同。需求 第乙個執行緒寫入 input 使用者,另乙個執行緒取讀取 out 使用者.實現讀乙個,寫乙個操作。共享資源源實體類,兩個執行緒將會對類中變數進行讀和寫操作 class res寫執行緒資源 class intthrad e...