wait() 方法的作用是使當前執行的執行緒進入等待,**執行到 wait 一行進入等待;當執行緒被喚醒時從 wait 下一行開始執行。
wait() 方法需要在 synchronized **塊中呼叫,否則會報錯。
wait() 方法會釋放鎖,其它執行緒可以競爭獲得鎖
wait() 方法有乙個帶時間引數的,當時間到了可以自動喚醒而不需要notify
notify() 方法的作用是用來通知其它在等待同一把鎖的執行緒,當使用 notify() 方法時,會隨機喚醒多個等待執行緒的其中乙個,進行等待獲取該鎖。
notify() 方法需要在 synchronized **塊中呼叫,否則會報錯。
notify() 方法不會立馬釋放鎖,(wait 是馬上釋放鎖的),需要等整個**執行完畢,才會釋放鎖,被通知的執行緒也不能馬上獲取鎖,需等 notify 的方法執行完之後,釋放了鎖,被通知的鎖才能獲取鎖。
notifyall() 通知所有等待同一把鎖的全部執行緒結束等待,進入可執行狀態,全部執行緒等待方法釋放鎖然後一起競爭這把鎖。
可以看到 執行緒1在呼叫 notify 之後並沒有馬上釋放掉鎖,而是執行完才釋放執行緒0 才能獲得鎖。public class tongxin
} catch (interruptedexception e)
system.out.println(thread.currentthread().getname() + "執行最後的操作" + new date());
}}).start();
new thread(new runnable() catch (interruptedexception e)
system.out.println(thread.currentthread().getname() + "執行最後的操作" + new date());}}
}).start(); }}
---執行結果
thread-0呼叫wait前sun jun 09 12:11:25 cst 2019
thread-1呼叫notify前sun jun 09 12:11:25 cst 2019
thread-1呼叫notify後sun jun 09 12:11:25 cst 2019
thread-1執行最後的操作sun jun 09 12:11:28 cst 2019
thread-0呼叫wait後sun jun 09 12:11:28 cst 2019
thread-0執行最後的操作sun jun 09 12:11:28 cst 2019
剛才發生了乙個小插曲,很納悶 notify 還沒執行完,wait 執行緒已經獲得鎖並執行了。
都會進入等待,但是 sleep 是不會釋放鎖的,而 wait 會釋放鎖。
後來才發現,thread.sleep(3000) 放到 synchronized 塊外面去了,鎖已經釋放掉了,所以才會發生上面的現象。
上面有提到,wait 方法和 notify 方法是需要結合 synchronized 來使用的,如果沒有 synchronized 是會報錯的。因為需要先獲取到物件鎖,然後在使用該鎖來呼叫 wait 和 notify。
wait 和 notify 是屬於 object 這個超類的方法,所以任何物件都能呼叫。
lock 中有個實現類叫 reentranlock,在 reentranlock 中可以借用 condition 物件實現執行緒間通訊。
condition 是乙個介面,await 方法相當於 object 中的 wait;signal 方法相當於 object 中的 notify;signalall 相當於 object 中的 notifyall。
可以看到,用法還是很簡單,reentranlock.lock() 獲得鎖,reentranlock.unlock() 釋放鎖。public class tongxin2 catch (interruptedexception e) finally
}}).start();
new thread(new runnable() catch (interruptedexception e) finally
}}).start(); }}
--- 執行結果
thread-0呼叫wait前sun jun 09 15:20:26 cst 2019
thread-1呼叫notify前sun jun 09 15:20:26 cst 2019
thread-1呼叫notify後sun jun 09 15:20:26 cst 2019
thread-1執行最後的操作sun jun 09 15:20:29 cst 2019
thread-0呼叫wait後sun jun 09 15:20:29 cst 2019
就執行緒間通訊而言,object 中的 wait notify 和 condition 中的 await signal 沒有多大區別。
只是前者是結合 synchronized 來使用,後者是結合 lock 來使用。
多執行緒 執行緒間通訊
學習思路 執行緒同步 鎖 wait notify join threadlocal 通過管道輸入 輸出流 字元流 位元組流 服務如果一直處於單執行緒訪問,那將毫無意義,多使用者訪問必然產生多執行緒,而多執行緒訪問必然離不開執行緒間通訊 多執行緒操作共享資源時勢必會產生執行緒安全的問題 也就是我們說的...
多執行緒3 執行緒間通訊
這兩種方法都要在同步 塊或同步方法中呼叫。都需要先獲得物件級別的鎖。只有兩個方法的物件鎖一致,即 物件監視器 一致,再能通過notify方法通知到執行wait方法的執行緒繼續執行。使用wait方法後,該執行緒會釋放物件鎖,並進入阻塞佇列等待被喚醒。notify方法喚醒wait方法後,該執行緒進入就緒...
142 多執行緒 執行緒間通訊
執行緒間通訊 其實就是多執行緒在操作同乙個資源。但是操作的動作不同 class res class input implements runnable public void run else x x 1 2 class output implements runnable public void ...