public class Factory {
public int num=0;
public static void main(String[] args) {
Factory factory=new Factory();
Producer producer=new Producer(factory);
Comsumer comsumer=new Comsumer(factory);
Thread t1=new Thread(producer,"生产者");
Thread t2=new Thread(comsumer,"消费者");
t1.start();
t2.start();
}
public synchronized void product() {
notifyAll();
num++;
System.out.println(""+Thread.currentThread().getName()+"正在生产第"+num+"个产品");
}
public synchronized void consume() {
if(num>0){
System.out.println(""+Thread.currentThread().getName()+"正在消费第"+num+"个产品");
num--;
}else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer implements Runnable{
private Factory factory;
public Producer(Factory factory) {
this.factory = factory;
}
@Override
public void run() {
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
factory.product();
}
}
}
class Comsumer implements Runnable{
private Factory factory;
public Comsumer(Factory factory) {
this.factory = factory;
}
@Override
public void run() {
while (true){
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
e.printStackTrace();
}
factory.consume();
}
}
}