一個關于Java Thread wait(),notify()的實用例(轉)
一個Java解決生產者-消費者同步問題的例子,很有參考價值的。- /////
- // ProducerConsumer.java
- //
- // 這是個很重要的Thread例子。需要注意的是:
- // wait() 必須在synchronized 函數或者代碼塊里面
- // wait()會讓已經獲得synchronized 函數或者代碼塊控制權的Thread暫時休息,并且喪失控制權
- // 這個時候,由于該線程喪失控制權并且進入等待,其他線程就能取得控制權,并且在適當情況下調用notifyAll()來喚醒wait()的線程。
- // 需要注意的是,被喚醒的線程由于已經喪失了控制權,所以需要等待喚醒它的線程結束操作,從而才能重新獲得控制權。
- //
- // 所以wait()的確是馬上讓當前線程喪失控制權,其他的線程可以乘虛而入。
- //
- // 所以wait()的使用,必須存在2個以上線程,而且必須在不同的條件下喚醒wait()中的線程。
- //
- //
- // 以下的例子:
- // ProductStack 是一個生產者跟消費者共享的同步機制,這個機制決定了什么情況生產者要wait(),什么情況消費者要wait()
- // 可以把ProductStack看作一個產品倉庫。當產品倉庫滿的時候,生產者線程需要wait(),從而放棄對產品倉庫的控制。
- // 這個時候消費者線程就可以進來了而取得倉庫的控制權。一旦消費者消費了產品,那么倉庫就不滿了。
- // 這個時候消費者線程就要notifyAll()生產者線程,讓等待的生產者線程喚醒。
- // 但是生產者被喚醒后不能馬上進行生產,因為它在wait()的時候已經喪失了對倉庫的控制權,所以就需要等待消費者線程結束操作,
- // 才能重新取得倉庫的控制權,再進行生產。
- //
- // 所以特別注意的是,notifyAll()并不是讓當前線程馬上讓出控制權,而只是讓其他wait()當中的線程喚醒而已,
- // 所以對不起,盡管我喚醒你,可你必須還是要等我用完倉庫才能進來。這點必須清楚。
- //
- // 相反,倉庫如果空的時候,消費者線程就會wait(),然后等待生產者線程來生產產品,生產者進程乘虛而入后,讓生產者線程生產產品
- // 并且喚醒消費者線程。這個情況跟上面就類似了。
- //
- ///
- 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();
- }
- }
- }
- }
posted on 2012-04-17 13:39 AlanLiu 閱讀(657) 評論(0) 編輯 收藏 所屬分類: java