Java生产者和消费者例子_动力节点Java学院整理

2025-05-29 0 69

生产者消费者(producer-consumer)问题,也称作有界缓冲区(bounded-buffer)问题,两个进程共享一个公共的固定大小的缓冲区。其中一个是生产者,用于将消息放入缓冲区;另外一个是消费者,用于从缓冲区中取出消息。问题出现在当缓冲区已经满了,而此时生产者还想向其中放入一个新的数据项的情形,其解决方法是让生产者此时进行休眠,等待消费者从缓冲区中取走了一个或者多个数据后再去唤醒它。同样地,当缓冲区已经空了,而消费者还想去取消息,此时也可以让消费者进行休眠,等待生产者放入一个或者多个数据时再唤醒它。

一,首先定义公共资源类,其中的变量number是保存的公共数据。

并且定义两个方法,增加number的值和减少number的值。由于多线程的原因,必须加上synchronized关键字,注意while判断的条件。

Java代码

二,分别定义生产

?

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
/**

* 公共资源类

*/

public class PublicResource {

private int number = 0;

/**

* 增加公共资源

*/

public synchronized void increace() {

while (number != 0) {

try {

wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

number++;

System.out.println(number);

notify();

}

/**

* 减少公共资源

*/

public synchronized void decreace() {

while (number == 0) {

try {

wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

number--;

System.out.println(number);

notify();

}

}

者线程和消费者线程,并模拟多次生产和消费,即增加和减少公共资源的number值

Java代码

?

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
/**

* 生产者线程,负责生产公共资源

*/

public class ProducerThread implements Runnable {

private PublicResource resource;

public ProducerThread(PublicResource resource) {

this.resource = resource;

}

@Override

public void run() {

for (int i = 0; i < 10; i++) {

try {

Thread.sleep((long) (Math.random() * 1000));

} catch (InterruptedException e) {

e.printStackTrace();

}

resource.increace();

}

}

}

/**

* 消费者线程,负责消费公共资源

*/

public class ConsumerThread implements Runnable {

private PublicResource resource;

public ConsumerThread(PublicResource resource) {

this.resource = resource;

}

@Override

public void run() {

for (int i = 0; i < 10; i++) {

try {

Thread.sleep((long) (Math.random() * 1000));

} catch (InterruptedException e) {

e.printStackTrace();

}

resource.decreace();

}

}

}

三,模拟多个生产者消费者操作公共资源的情形,结果须保证是在允许的范围内。

Java代码

?

1

2

3

4

5

6

7

8

9

10

11
public class ProducerConsumerTest {

public static void main(String[] args) {

PublicResource resource = new PublicResource();

new Thread(new ProducerThread(resource)).start();

new Thread(new ConsumerThread(resource)).start();

new Thread(new ProducerThread(resource)).start();

new Thread(new ConsumerThread(resource)).start();

new Thread(new ProducerThread(resource)).start();

new Thread(new ConsumerThread(resource)).start();

}

}

以上所述是小编给大家介绍的Java生产者消费者例子,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java生产者和消费者例子_动力节点Java学院整理 https://www.kuaiidc.com/116469.html

相关文章

发表评论
暂无评论