生产者消费者

生产者消费者

维基百科解释:

In computing, the producer–consumer problem[1][2] (also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue. The producer’s job is to generate data, put it into the buffer, and start again. At the same time, the consumer is consuming the data (i.e., removing it from the buffer), one piece at a time. The problem is to make sure that the producer won’t try to add data into the buffer if it’s full and that the consumer won’t try to remove data from an empty buffer.

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* @Author: cuzz
* @Date: 2019/4/6 13:03
* @Description: 生产者消费者
*/
public class ProducerConsumerDemo {
public static void main(String[] args) {
Container container = new Container();
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(() -> container.produce());
executor.execute(() -> container.consume());
executor.shutdown();
}
}

class Container {
private List<Integer> list = new LinkedList<>();
private final int MAX_SIZE = 5;

private Random random = new Random();

public void produce() {
while (true) {
synchronized (this) {
try {
while (list.size() >= MAX_SIZE) {
wait();
}
int i = random.nextInt();
System.out.println("produce..." + i);
list.add(i);
notify();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public void consume() {
while (true) {
try {
synchronized (this) {
while (list.isEmpty()) {
wait();
}
int i = list.remove(0);
System.out.println("consume..." + i);
notify();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}