- 问题描述
- 数据结构:
- 规则:
- 生产/消费者同时操作缓存区。
- 当缓存区为空的时候,消费者不能消费,即消费者阻塞。
- 当缓存区为满的时候,生产者不能生产,即生产者阻塞。
- 生产者之间互斥,消费者之间同步。
- 代码实现
- 使用wait() / notifyAll(),简单实现:
- 当缓存区满或者空的时候,调用wait方法等待,当生产者生产一个资源或者消费者消费一个资源之后,唤醒所有线程。
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 commonsstring@gmail.com
*/
static class Procuder implements Runnable{
@Override
public void run() {
for(int i = 0; i < 10; i++) {
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 commonsstring@gmail.com
*
*/
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();
}
}
}
}
}