线程协作之生产者消费者模型

线程协作之生产者消费者模型


生产者和消费者共同协助,管理一块缓冲区

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package demo.study.ThreadTest;

public class PC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
Producer producer = new Producer(container);
Consumer consumer = new Consumer(container);
consumer.start();
producer.start();
}
}
class Chicken{
int id;

public Chicken(int id) {
this.id = id;
}
}
//生产者
class Producer extends Thread{

SynContainer container = new SynContainer();
public Producer(SynContainer container){
this.container=container;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println("生产了"+i+"只鸡");
try {
container.push(new Chicken(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//消费者
class Consumer extends Thread{
SynContainer container = new SynContainer();
public Consumer(SynContainer container){
this.container=container;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
try {
System.out.println("消费了"+ this.container.pop().id+"只鸡");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//容器(缓冲区)
class SynContainer{
Chicken[] chickens=new Chicken[10];
int count = 0;
//添加鸡
public synchronized void push(Chicken chicken) throws InterruptedException {
//如果鸡的数量等于容器大小(容器满)
if (count==chickens.length){
//生产者等待
this.wait();
}
//通知消费者消费
this.notifyAll();
chickens[count]=chicken;
count++;

}

public synchronized Chicken pop() throws InterruptedException {
if (count==0){
//通知生产者生产
notifyAll();
//消费者等待
wait();
}
count--;
return chickens[count];
}
}
-------------本文结束感谢您的阅读-------------