notify和notifyAll的區別

2021-09-12 11:45:15 字數 1567 閱讀 4778

鎖池entrylist

等待池waitset

鎖池

假設執行緒a已經擁有了某個物件(不是類)的鎖,而其他執行緒b,c想要呼叫這個物件的某個synchronized方法(或者塊),由於b,c執行緒在進入物件的synchronized方法(或者塊)之前就必須先獲得該物件鎖的擁有權,而恰巧該物件的鎖目前正被執行緒a所占用,此時b,c執行緒就會被阻塞,進入乙個地方去等待鎖的釋放,這個地方便是該物件的鎖池

等待池

假設執行緒a呼叫了某個物件的wait()方法,執行緒a就會釋放該物件的鎖,同時執行緒a就進入到了該物件的等待池中,進入到等待池中的執行緒不會去競爭改物件的鎖

notifyall會讓所有處於等待池的執行緒全部進入鎖池去競爭獲取鎖的機會

notify只會隨機選取乙個處於等待池中的執行緒進入鎖池去競爭獲取鎖的機會

我們用例子演示說明

開3個等待的執行緒,乙個通知的執行緒,通知的執行緒裡面呼叫notify方法

public

class

showdemo

catch

(interruptedexception e)}}

};runnable notifytask =

newrunnable()

}}; thread thread1 =

newthread

(waittask,

"thread1");

thread thread2 =

newthread

(waittask,

"thread2");

thread thread3 =

newthread

(waittask,

"thread3");

thread1.

start()

; thread2.

start()

; thread3.

start()

;// 確保thread1,thread2,thread3都啟動後,啟動thread4

trycatch

(interruptedexception e)

thread thread4 =

newthread

(notifytask,

"thread4");

thread4.

start()

;}}

看到只有乙個執行緒結束了,其餘2個執行緒一直阻塞。

thread2 wait

thread3 wait

thread1 wait

thread2 notify

將notifytask中的notify換成notifyall,輸入如下,可以看到3個執行緒都正常結束

thread1 wait

thread2 wait

thread3 wait

thread3 notify

thread2 notify

thread1 notify

wait 和notify 入門例子

也就是說,wait 會讓出物件鎖,同時,當前執行緒休眠,等待被喚醒,如果不被喚醒,就一直等在那兒。notify 並不會讓當前執行緒休眠,但會喚醒休眠的執行緒。先看第乙個例子!public class threadf catch interruptedexception e system.out.pr...

Java wait和notify結合使用

1 示例 public class testsyncro2 thread t2 new thread new runnable t1.start t2.start class customer catch exception ex this.amount amount system.out.prin...

notify 和notifyAll 主要區別

notify 和notifyall 都是object物件用於通知處在等待該物件的執行緒的方法。void notify 喚醒乙個正在等待該物件的執行緒。void notifyall 喚醒所有正在等待該物件的執行緒。兩者的最大區別在於 notifyall使所有原來在該物件上等待被notify的執行緒統統...