一個關於Java Thread wait(),notify()的實用例

/////
// ProducerConsumer.java
//
// @author 葉雨
//
// 這是個很重要的Thread例子。須要注意的是:
// wait() 必須在synchronized 函數或者代碼塊裏面
// wait()會讓已經得到synchronized 函數或者代碼塊控制權的Thread暫時休息,而且喪失控制權
// 這個時候,因爲該線程喪失控制權而且進入等待,其餘線程就能取得控制權,而且在適當狀況下調用notifyAll()來喚醒wait()的線程。
// 須要注意的是,被喚醒的線程因爲已經喪失了控制權,因此須要等待喚醒它的線程結束操做,從而才能從新得到控制權。
//
// 因此wait()的確是立刻讓當前線程喪失控制權,其餘的線程能夠乘虛而入。
//
// 因此wait()的使用,必須存在2個以上線程,並且必須在不一樣的條件下喚醒wait()中的線程。
//
//
// 如下的例子:
// ProductStack 是一個生產者跟消費者共享的同步機制,這個機制決定了什麼狀況生產者要wait(),什麼狀況消費者要wait()
// 能夠把ProductStack看做一個產品倉庫。當產品倉庫滿的時候,生產者線程須要wait(),從而放棄對產品倉庫的控制。
// 這個時候消費者線程就能夠進來了而取得倉庫的控制權。一旦消費者消費了產品,那麼倉庫就不滿了。
// 這個時候消費者線程就要notifyAll()生產者線程,讓等待的生產者線程喚醒。
// 可是生產者被喚醒後不能立刻進行生產,由於它在wait()的時候已經喪失了對倉庫的控制權,因此就須要等待消費者線程結束操做,
// 才能從新取得倉庫的控制權,再進行生產。
//
// 因此特別注意的是,notifyAll()並非讓當前線程立刻讓出控制權,而只是讓其餘wait()當中的線程喚醒而已,
// 因此對不起,儘管我喚醒你,可你必須仍是要等我用完倉庫才能進來。這點必須清楚。
//
// 相反,倉庫若是空的時候,消費者線程就會wait(),而後等待生產者線程來生產產品,生產者進程乘虛而入後,讓生產者線程生產產品
// 而且喚醒消費者線程。這個狀況跟上面就相似了。
//
///

package cn.com.dang;
 
public class ProducerConsumer {
      public static void main(String[] args) {
           ProductStack ps = new ProductStack();
           Producer p = new Producer(ps, "生產者1");
           Consumer c = new Consumer(ps, "消費者1");
           new Thread(p).start();
           new Thread(c).start();
      }
}
 
class Product {
      int id;
 
      private String producedBy = "N/A";
 
      private String consumedBy = "N/A";
 
      // 構造函數,指明產品ID以及生產者名字。
      Product(int id, String producedBy) {
           this.id = id;
           this.producedBy = producedBy;
      }
 
      // 消費,須要指明消費者名字
      public void consume(String consumedBy) {
           this.consumedBy = consumedBy;
      }
 
      public String toString() {
           return "Product : " + id + ", produced by " + producedBy
                      + ", consumed by " + consumedBy;
      }
 
      public String getProducedBy() {
           return producedBy;
      }
 
      public void setProducedBy(String producedBy) {
           this.producedBy = producedBy;
      }
 
      public String getConsumedBy() {
           return consumedBy;
      }
 
      public void setConsumedBy(String consumedBy) {
           this.consumedBy = consumedBy;
      }
 
}
 
// 這個class就是倉庫,是生產者跟消費者共同爭奪控制權的同步資源
class ProductStack {
      int index = 0;
 
      Product[] arrProduct = new Product[6];
 
      // push使用來讓生產者放置產品的
      public synchronized void push(Product product) {
           // 若是倉庫滿了
           while (index == arrProduct.length) // 這裏原本能夠用if(),可是若是catch
                                            // exception會出問題,讓滿的index越界
           {
                 try {
                      // here, "this" means the thread that is using "push"
                      // so in this case it's a producer thread instance.
                      // the BIG difference between sleep() and wait() is, once
                      // wait(),
                      // the thread won't have the lock anymore
                      // so when a producer wait() here, it will lost the lock of
                      // "push()"
                      // While sleep() is still keeping this lock
                      // Important: wait() and notify() should be in "synchronized"
                      // block
 
                      System.out.println(product.getProducedBy() + " is waiting.");
                      // 等待,而且從這裏退出push()
                      wait();
                 } catch (InterruptedException e) {
                      e.printStackTrace();
                 }
           }
           System.out.println(product.getProducedBy() + " sent a notifyAll().");
 
           // 由於咱們不肯定有沒有線程在wait(),因此咱們既然生產了產品,就喚醒有可能等待的消費者,讓他們醒來,準備消費
           notifyAll();
           // 注意,notifyAll()之後,並無退出,而是繼續執行直到完成。
           arrProduct[index] = product;
           index++;
           System.out.println(product.getProducedBy() + " 生產了: " + product);
      }
 
      // pop用來讓消費者取出產品的
      public synchronized Product pop(String consumerName) {
           // 若是倉庫空了
           while (index == 0) {
                 try {
                      // here will be the consumer thread instance will be waiting ,
                      // because empty
                      System.out.println(consumerName + " is waiting.");
                      // 等待,而且從這裏退出pop()
                      wait();
                 } catch (InterruptedException e) {
                      e.printStackTrace();
                 }
           }
 
           System.out.println(consumerName + " sent a notifyAll().");
           // 由於咱們不肯定有沒有線程在wait(),因此咱們既然消費了產品,就喚醒有可能等待的生產者,讓他們醒來,準備生產
           notifyAll();
           // 注意,notifyAll()之後,並無退出,而是繼續執行直到完成。
           // 取出產品
           index--;
           Product product = arrProduct[index];
           product.consume(consumerName);
           System.out.println(product.getConsumedBy() + " 消費了: " + product);
           return product;
      }
}
 
class Producer implements Runnable {
      String name;
 
      ProductStack ps = null;
 
      Producer(ProductStack ps, String name) {
           this.ps = ps;
           this.name = name;
      }
 
      public void run() {
           for (int i = 0; i < 20; i++) {
                 Product product = new Product(i, name);
                 ps.push(product);
                 try {
                      Thread.sleep((int) (Math.random() * 200));
                 } catch (InterruptedException e) {
                      e.printStackTrace();
                 }
           }
      }
}
 
class Consumer implements Runnable {
      String name;
 
      ProductStack ps = null;
 
      Consumer(ProductStack ps, String name) {
           this.ps = ps;
           this.name = name;
      }
 
      public void run() {
           for (int i = 0; i < 20; i++) {
                 Product product = ps.pop(name);
                 try {
                      Thread.sleep((int) (Math.random() * 1000));
                 } catch (InterruptedException e) {
                      e.printStackTrace();
                 }
           }
      }
}
相關文章
相關標籤/搜索