⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 waitnotifyexam.java

📁 Java程序设计实用教程源代码 本书源代码按章分别放置在不同的文件夹中,所有程序均在JDK1.6环境下编译运行正常,除了第13章需要建立ODBC数据源之外,其他程序只要有Java运行环境即可直接运行
💻 JAVA
字号:
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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -