版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37014990/article/details/82659936
- 问题描述
- 数据结构:
- 生产者/消费者
- 缓存区(共享资源)
- 规则:
- 生产/消费者同时操作缓存区。
- 当缓存区为空的时候,消费者不能消费,即消费者阻塞。
- 当缓存区为满的时候,生产者不能生产,即生产者阻塞。
- 生产者之间互斥,消费者之间同步。
- 数据结构:
- 代码实现
- 使用wait() / notifyAll(),简单实现:
- 当缓存区满或者空的时候,调用wait方法等待,当生产者生产一个资源或者消费者消费一个资源之后,唤醒所有线程。
- 使用wait() / notifyAll(),简单实现:
public class Model_P_C {
// 资源数
public static int count = 0;
// 缓冲区总大小
public final static int FULL = 10;
public static String L = "";
public static void main(String[] args) {
new Thread(new Procuder()).start();
new Thread(new Consumer()).start();
new Thread(new Procuder()).start();
new Thread(new Consumer()).start();
new Thread(new Procuder()).start();
new Thread(new Consumer()).start();
new Thread(new Procuder()).start();
}
/**
* 生产者
* @author [email protected]
*/
static class Procuder implements Runnable{
@Override
public void run() {
// 运行10次
for(int i = 0; i < 10; i++) {
// 等待3s
try {
Thread.sleep(3000);
// 生产
synchronized(L) {
// 当缓存区满的时候, 等待消费者消费
while(count == FULL) {
L.wait();
}
// 生产者生产
count++;
System.out.println(Thread.currentThread().getName()
+ " 生产者生产, 缓冲区:" + count);
// 唤醒所有生产者和消费者
L.notifyAll();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 消费者
* @author [email protected]
*
*/
static class Consumer implements Runnable {
@Override
public void run() {
for(int i = 0; i < 10; i++) {
try {
Thread.sleep(300);
synchronized(L) {
while(count == 0) {
L.wait();
}
// 消费者消费
count--;
System.out.println(Thread.currentThread().getName()
+ " 消费者消费, 缓冲区:" + count);
L.notifyAll();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}