生产者消费者

维基百科解释:

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.

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();
}
}
}
}
-------------本文结束感谢您的阅读-------------

本文标题:生产者消费者

文章作者:cuzz

发布时间:2019年04月06日 - 22:04

最后更新:2019年07月16日 - 19:07

原始链接:http://blog.cuzz.site/2019/04/06/生产者消费者/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

请博主吃包辣条
0%