kim.zhang

风在前,无惧!


  • 首页

  • 标签42

  • 分类12

  • 归档94

  • 搜索

生产者与消费者.md

发表于 2020-08-10 更新于 2021-11-21 分类于 并发
本文字数: 1.7k 阅读时长 ≈ 2 分钟

栗子1:使用wait/notify方法来实现

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
public class ProducerAndConsumerExample {
public static void main(String[] args) {
Container container = new Container();
new Thread(new Consumer(container)).start();
new Thread(new Producer(container)).start();
}
}


class Consumer implements Runnable {

private Container container;

public Consumer(Container container) {
this.container = container;
}

@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
container.take();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

class Producer implements Runnable {

private Container container;

public Producer(Container container) {
this.container = container;
}

@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
container.put();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

// 实现类似于阻塞队列的容器
class Container {
private Integer maxSize = 30;
private LinkedList<Integer> queue;

public Container() {
queue = new LinkedList<>();
}

public synchronized void put() throws InterruptedException {
// 队列已满,阻塞等待,使用while而不是使用if
while (this.queue.size() == maxSize) {
this.wait();
}
this.queue.add(1);
System.out.println("添加到容器,容器内还有" + this.queue.size() + "个数据");
// 通知消费者取数据
this.notifyAll();
}

public synchronized void take() throws InterruptedException {
// 队列为空,阻塞等待,使用while而不是使用if
while (this.queue.size() == 0) {
this.wait();
}
this.queue.poll();
System.out.println("取出数据,容器内还有" + this.queue.size() + "个数据");
// 通知生产者生产数据
this.notifyAll();
}
}
一毛也是爱~
Kim.Zhang 微信支付

微信支付

# 并发基础
线程的启动与终止.md
创建线程的方式.md
  • 文章目录
  • 站点概览
Kim.Zhang

Kim.Zhang

且行且珍惜
94 日志
12 分类
42 标签
E-Mail Weibo
  1. 1. 栗子1:使用wait/notify方法来实现
粵ICP备19091267号 © 2019 – 2022 Kim.Zhang | 629k | 9:32
本站总访问量 4 次 | 有 309 人看我的博客啦 |
博客全站共176.7k字
载入天数...载入时分秒...
0%