生产者–消费者(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();
}
}
|
相关文章
猜你喜欢
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
Hadoop之NameNode Federation图文详解
2025-05-29 18 -
2025-05-25 75
-
2025-06-04 25
-
2025-05-29 89
-
2025-05-29 51
热门评论