```java
class Product {
int numOfProduct = 0;
public synchronized void addProdect() throws InterruptedException {
if(this.numOfProduct<20){
this.numOfProduct++;
System.out.println("生产者开始生产第"+this.numOfProduct+"个产品");
notify();
}else{
wait();
}
}
public synchronized void subProdect() throws InterruptedException {
if(this.numOfProduct>0){
System.out.println("消费者开始消费第"+this.numOfProduct+"个产品");
this.numOfProduct--;
notify();
}else{
wait();
}
}
}
class Productor implements Runnable {
private Product p;
public Productor(Product p) {
this.p = p;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
p.addProdect();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Customerw implements Runnable{
private Product p;
public Customerw(Product p) {
this.p = p;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
p.subProdect();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Exchange {
public static void main(String[] args) {
Product p=new Product();
Customerw c=new Customerw(p);
Productor pro=new Productor(p);
Thread t1=new Thread(c);
Thread t2=new Thread(pro);
t1.start();
t2.start();
}
}