1. 程式人生 > >轉:【Java並發編程】之十二:線程間通信中notifyAll造成的早期通知問題(含代碼)

轉:【Java並發編程】之十二:線程間通信中notifyAll造成的早期通知問題(含代碼)

data light lan 添加項 article util tool 元素 seconds

轉載請註明出處:http://blog.csdn.net/ns_code/article/details/17229601

如果線程在等待時接到通知,但線程等待的條件還不滿足,此時,線程接到的就是早期通知,如果條件滿足的時間很短,但很快又改變了,而變得不再滿足,這時也將發生早期通知。這種現象聽起來很奇怪,下面通過一個示例程序來說明問題。

很簡單,兩個線程等待刪除List中的元素,同時另外一個線程正要向其中添加項目。代碼如下:

[java] view plain copy
  1. import java.util.*;
  2. public class EarlyNotify extends Object {
  3. private List list;
  4. public EarlyNotify() {
  5. list = Collections.synchronizedList(new LinkedList());
  6. }
  7. public String removeItem() throws InterruptedException {
  8. print("in removeItem() - entering");
  9. synchronized ( list ) {
  10. if ( list.isEmpty() ) { //這裏用if語句會發生危險
  11. print("in removeItem() - about to wait()");
  12. list.wait();
  13. print("in removeItem() - done with wait()");
  14. }
  15. //刪除元素
  16. String item = (String) list.remove(0);
  17. print("in removeItem() - leaving");
  18. return item;
  19. }
  20. }
  21. public void addItem(String item) {
  22. print("in addItem() - entering");
  23. synchronized ( list ) {
  24. //添加元素
  25. list.add(item);
  26. print("in addItem() - just added: ‘" + item + "‘");
  27. //添加後,通知所有線程
  28. list.notifyAll();
  29. print("in addItem() - just notified");
  30. }
  31. print("in addItem() - leaving");
  32. }
  33. private static void print(String msg) {
  34. String name = Thread.currentThread().getName();
  35. System.out.println(name + ": " + msg);
  36. }
  37. public static void main(String[] args) {
  38. final EarlyNotify en = new EarlyNotify();
  39. Runnable runA = new Runnable() {
  40. public void run() {
  41. try {
  42. String item = en.removeItem();
  43. print("in run() - returned: ‘" +
  44. item + "‘");
  45. } catch ( InterruptedException ix ) {
  46. print("interrupted!");
  47. } catch ( Exception x ) {
  48. print("threw an Exception!!!\n" + x);
  49. }
  50. }
  51. };
  52. Runnable runB = new Runnable() {
  53. public void run() {
  54. en.addItem("Hello!");
  55. }
  56. };
  57. try {
  58. //啟動第一個刪除元素的線程
  59. Thread threadA1 = new Thread(runA, "threadA1");
  60. threadA1.start();
  61. Thread.sleep(500);
  62. //啟動第二個刪除元素的線程
  63. Thread threadA2 = new Thread(runA, "threadA2");
  64. threadA2.start();
  65. Thread.sleep(500);
  66. //啟動增加元素的線程
  67. Thread threadB = new Thread(runB, "threadB");
  68. threadB.start();
  69. Thread.sleep(10000); // wait 10 seconds
  70. threadA1.interrupt();
  71. threadA2.interrupt();
  72. } catch ( InterruptedException x ) {}
  73. }
  74. }

執行結果如下:

技術分享

分析:首先啟動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造成的早期通知問題(含代碼)