📄 waitnotifyexam.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 + -