利用多线程模拟生产消费模式。假设有2个生产者,3个消费者,生产者负责生产商品,消费者负责购买。如果商品数量为0,则消费者暂停购买,直到有商品了才能继续,每个生产者最多生产10个商品
import java.util.LinkedList;
public class Main {
public LinkedList<Integer> buffer = new LinkedList<>();
public int capacity = 5;
public int productionLimit = 10;
public int producedCount = 0;
public static void main(String[] args) {
Main demo = new Main();
demo.start();
}
public void start() {
Thread producer1 = new Thread(new Producer(), "生产者1");
Thread producer2 = new Thread(new Producer(), "生产者2");
Thread consumer1 = new Thread(new Consumer(), "消费者1");
Thread consumer2 = new Thread(new Consumer(), "消费者2");
Thread consumer3 = new Thread(new Consumer(), "消费者3");
producer1.start();
producer2.start();
consumer1.start();
consumer2.start();
consumer3.start();
}
class Producer implements Runnable {
public void run() {
for (int i = 0; i < productionLimit; i++) { //如果缓冲区已满等待消费者消费
synchronized (buffer) {
while (buffer.size() == capacity) {
try {
buffer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int production = producedCount++; // 生产商品通知消费者
buffer.add(production);
System.out.println(Thread.currentThread().getName() + " 生产: " + production);
buffer.notifyAll();
}
}
}
}
class Consumer implements Runnable {
public void run() {
while (true) {
synchronized (buffer) {// 如果缓冲区为空等待生产者生产
while (buffer.isEmpty()) {
try {
buffer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int consumption = buffer.removeFirst();// 消费商品并通知生产者
System.out.println(Thread.currentThread().getName() + " 消费: " + consumption);
buffer.notifyAll();
if (consumption == productionLimit - 1) {// 如果所有商品都已消费完结束消费
break;
}
}
}
}
}
}