消费者与生产者
package com.xiaobai.shangguigu.Test;
class Clerk {//店员
private int productNum = 0;//产品的数量
public synchronized void addProductNum() {
if (productNum > 20) {
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}else {
productNum++;
System.out.println(Thread.currentThread().getName() + "生产了第" + productNum + "个产品");
notifyAll();
}
}
public synchronized void minusProductNum() {
if (productNum <= 0) {
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} else {
System.out.println(Thread.currentThread().getName() + "消费了第" + productNum + "个产品");
productNum--;
notifyAll();
}
}
}
class Producer extends Thread {//生产者
private Clerk clerk;
public Producer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
while (true) {
System.out.println("生产者开始生产");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
clerk.addProductNum();
}
}
}
class Consumer extends Thread {//消费者
private Clerk clerk;
public Consumer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
while (true) {
System.out.println("消费者正在消费");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
clerk.minusProductNum();
}
}
}
//生产者和消费者实例
public class ProducerConsumerTest {
public static void main(String[] args) {
Clerk clerk = new Clerk();
Producer producer = new Producer(clerk);
Consumer consumer = new Consumer(clerk);
producer.setName("生产者1");
consumer.setName("消费者1");
producer.start();
consumer.start();
}
}