1、概述
生产者和消费者问题是一个经典的线程同步问题。生产者(Producer)生产产品(Product),放入仓库(Repertory);消费者(Consumer)消费产品,从仓库里获取。仓库爆满时生产者等待消费者消费,仓库为空时消费者等待生产者生产。2、实现
2.1、synchronized
生产者Producer:
public class Producer implements Runnable {
private static final String TAG = "Producer";
private Repertory mRepertory;
Producer(Repertory repertory) {
mRepertory = repertory;
}
@Override
public void run() {
Object product = new Object();
mRepertory.produce(product);
}
}
消费者Consumer:
public class Consumer implements Runnable {
private static final String TAG = "Consumer";
private Repertory mRepertory;
Consumer(Repertory repertory) {
mRepertory = repertory;
}
@Override
public void run() {
mRepertory.consume();
}
}
仓库Repertory1:
public class Repertory1 implements Repertory {
private static final String TAG = "Repertory1";
private static final int MAX_SIZE = 100;
private LinkedList<Object> list = new LinkedList<>();
@Override
public synchronized