生产者消费者模式实现(synchronized、wait和notify方式)
一. 基本流程
生产者在缓冲区未满时生产数据,消费者在缓冲区有数据时从缓冲区中取数据。
如果缓冲区已经满了,则生产者线程阻塞;
如果缓冲区为空,那么消费者线程阻塞。
二. 对象类型
- 生产者
- 消费者
- 仓库
- 产品
三. 代码实现
- 产品
package xyz.yyaosen.produce;
import java.util.ArrayList;
import java.util.List;
public class Produce {
// 缓冲区-产品
private static List<Integer> produce = new ArrayList<Integer>();
// 缓冲区-容量
private static final int VOLUME = 10;
// 状态锁
private Object lock;
public Produce() {
}
public Produce(Object lock) {
// TODO Auto-generated constructor stub
this.lock = lock;
}
// 生产
public void add() {
synchronized (lock) {
if (produce.size() < VOLUME) {
produce.add(1);
System.out.println("生产者" + Thread.currentThread().getId() + ",产品数量(+1):" + produce.size());
lock.notifyAll();
} else {
try {
System.out
.println("生产者" + Thread.currentThread().getId() + ",产品数量(/):" + produce.size() + "/等待...");
lock.wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// 消费
public void remove() {
synchronized (lock) {
if (produce.size() > 0) {
produce.remove(produce.size() - 1);
System.out.println("消费者" + Thread.currentThread().getId() + ",产品数量(-1):" + produce.size());
lock.notifyAll();
} else {
try {
System.out
.println("消费者" + Thread.currentThread().getId() + ",产品数量(/):" + produce.size() + "/等待...");
lock.wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
- 消费者线程
package xyz.yyaosen.produce;
public class ConsumerThread implements Runnable {
// 产品实例
Produce produce = new Produce(new Object());
// run
public void run() {
while (true) {
produce.remove();
}
}
}
- 生产者线程
package xyz.yyaosen.produce;
public class ProduceThread implements Runnable {
// 产品实例
Produce produce = new Produce(new Object());
// run
public void run() {
while (true) {
produce.add();
}
}
}
- 入口类
package xyz.yyaosen.produce;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 消费者线程
ConsumerThread consumerThread = new ConsumerThread();
Thread cThread1 = new Thread(consumerThread);
Thread cThread2 = new Thread(consumerThread);
// 生产者线程
ProduceThread produceThread = new ProduceThread();
Thread pThread1 = new Thread(produceThread);
Thread pThread2 = new Thread(produceThread);
cThread1.start();
cThread2.start();
pThread1.start();
pThread2.start();
}
}
5.执行结果