維基百科解釋:java
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.dom
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
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(); } } } } |