waitnotifyexam.java

来自「Java程序设计实用教程源代码 本书源代码按章分别放置在不同的文件夹中,所有程」· Java 代码 · 共 60 行

JAVA
60
字号
class Product {
  private int counter = 1;
  private String name = "产品";
  private boolean bFlag = false;
  public synchronized void produce(String name, int counter) {
    try {
      if (bFlag)  //bFlag为true不能生产,需要等待消费完
        wait();
    }
    catch (Exception e) {}
    this.name = name;
    this.counter = counter;
    System.out.println("生产Product " + name + counter);
    bFlag = true;
    notify();    //唤醒消费
  }
  public synchronized void custome() {
    try {
      if (!bFlag)    //bFlag为flase 不能消费,需等待生产
        wait();
    }
    catch (Exception e) {}
    System.out.println("消费Product " + name + counter);
    bFlag = false;
    notify();   //唤醒生产
  }
}
class Producer implements Runnable {
  Product product;
  public Producer(Product obj) {
    product = obj;
  }
  public void run() {
    int i = 1;
    while (i <= 5) {//此处为了使程序不无限循环,限制只生产5个产品
      product.produce("豪华轿车", i++);
    }
  }
}
class Customer implements Runnable {
  Product product;
  public Customer(Product obj) {
    product = obj;
  }
  public void run() {
    int i = 1;
    while (i <= 5) {//此处对应前面生产产品的数量
      i++;
      product.custome();
    }
  }
} 
public class waitNotifyExam {
  public static void main(String[] args) {
    Product p = new Product();
    new Thread(new Producer(p)).start();
    new Thread(new Customer(p)).start();
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?