轉:【Java並發編程】之十二:線程間通信中notifyAll造成的早期通知問題(含代碼)
轉載請註明出處:http://blog.csdn.net/ns_code/article/details/17229601
如果線程在等待時接到通知,但線程等待的條件還不滿足,此時,線程接到的就是早期通知,如果條件滿足的時間很短,但很快又改變了,而變得不再滿足,這時也將發生早期通知。這種現象聽起來很奇怪,下面通過一個示例程序來說明問題。
很簡單,兩個線程等待刪除List中的元素,同時另外一個線程正要向其中添加項目。代碼如下:
[java] view plain copy- import java.util.*;
- public class EarlyNotify extends Object {
- private List list;
- public EarlyNotify() {
- list = Collections.synchronizedList(new LinkedList());
- }
- public String removeItem() throws InterruptedException {
- print("in removeItem() - entering");
- synchronized ( list ) {
- if ( list.isEmpty() ) { //這裏用if語句會發生危險
- print("in removeItem() - about to wait()");
- list.wait();
- print("in removeItem() - done with wait()");
- }
- //刪除元素
- String item = (String) list.remove(0);
- print("in removeItem() - leaving");
- return item;
- }
- }
- public void addItem(String item) {
- print("in addItem() - entering");
- synchronized ( list ) {
- //添加元素
- list.add(item);
- print("in addItem() - just added: ‘" + item + "‘");
- //添加後,通知所有線程
- list.notifyAll();
- print("in addItem() - just notified");
- }
- print("in addItem() - leaving");
- }
- private static void print(String msg) {
- String name = Thread.currentThread().getName();
- System.out.println(name + ": " + msg);
- }
- public static void main(String[] args) {
- final EarlyNotify en = new EarlyNotify();
- Runnable runA = new Runnable() {
- public void run() {
- try {
- String item = en.removeItem();
- print("in run() - returned: ‘" +
- item + "‘");
- } catch ( InterruptedException ix ) {
- print("interrupted!");
- } catch ( Exception x ) {
- print("threw an Exception!!!\n" + x);
- }
- }
- };
- Runnable runB = new Runnable() {
- public void run() {
- en.addItem("Hello!");
- }
- };
- try {
- //啟動第一個刪除元素的線程
- Thread threadA1 = new Thread(runA, "threadA1");
- threadA1.start();
- Thread.sleep(500);
- //啟動第二個刪除元素的線程
- Thread threadA2 = new Thread(runA, "threadA2");
- threadA2.start();
- Thread.sleep(500);
- //啟動增加元素的線程
- Thread threadB = new Thread(runB, "threadB");
- threadB.start();
- Thread.sleep(10000); // wait 10 seconds
- threadA1.interrupt();
- threadA2.interrupt();
- } catch ( InterruptedException x ) {}
- }
- }
執行結果如下:
分析:首先啟動threadA1,threadA1在removeItem()中調用wait(),從而釋放list上的對象鎖。再過500ms,啟動threadA2,threadA2調用removeItem(),獲取list上的對象鎖,也發現列表為空,從而在wait()方法處阻塞,釋放list上的對象鎖。再過500ms後,啟動threadB,並調用addItem,獲得list上的對象鎖,並在list中添加一個元素,同時用notifyAll通知所有線程。
threadA1和threadA2都從wait()返回,等待獲取list對象上的對象鎖,並試圖從列表中刪除添加的元素,這就會產生麻煩,只有其中一個操作能成功。假設threadA1獲取了list上的對象鎖,並刪除元素成功,在退出synchronized代碼塊時,它便會釋放list上的對象鎖,此時threadA2便會獲取list上的對象鎖,會繼續刪除list中的元素,但是list已經為空了,這便會拋出IndexOutOfBoundsException。
要避免以上問題只需將wait外圍的if語句改為while循環即可,這樣當list為空時,線程便會繼續等待,而不會繼續去執行刪除list中元素的代碼。
修改後的執行結果如下:
總結:在使用線程的等待/通知機制時,一般都要在while循環中調用wait()方法,滿足條件時,才讓while循環退出,這樣一般也要配合使用一個boolean變量(或其他能判斷真假的條件,如本文中的list.isEmpty()),滿足while循環的條件時,進入while循環,執行wait()方法,不滿足while循環的條件時,跳出循環,執行後面的代碼。
轉:【Java並發編程】之十二:線程間通信中notifyAll造成的早期通知問題(含代碼)