生产者消费者模型主要结构如下,是一个典型的线程同步的案例。下面就来使用java做几种线程同步的方式来实现以下该模型
确保一个生产者消费者模型的稳定运行的前提有以下几个
- 生成者应该具备持续生成的能力
- 消费者应该具备持续消费的能力
- 生产者的生成和消费消费有一定的阀值,如生成总量到100需要停止生产,通知消费;消费到0的时候停止消费开始生产;
wait,notify方案
wait,notify方案 主要是通过,使用对象的wait方法和notify方法来实现线程的切换执行。其中我们可以看到对象的wait和notify或者notifyAll方法都是调用native的对应的方法来处理,追溯到最后也还是控制cpu进行不同的时间片的切换
下面这个例子比较简单,模拟一个生产速度大于消费速度的这样一个案例,在生产到阀值的时候停止生产通知消费者进行消费(wait)。消费者在消费到一定阀值的时候停止消费通知生产者进行生产(notifyall)
public class TestWaitNotifyConsumerAndProducer {
/*当前生成数量*/
static int currentNum = 0;
/*最大生成数量*/
static int MAX_NUM = 10;
/*最小消费数量*/
static int MIN_NUM = 0;
/*wait和notify控制对象*/
private static final String lock = "lock";
public static void main(String args[]) {
//创建一个生产者
new Thread(new Producer()).start();
//创建两个消费者
new Thread(new Consumer()).start();
new Thread(new Consumer()).start();
}
static class Producer implements Runnable {
public void product() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock) {
currentNum++;
System.out.println("Producer now product num:" + currentNum);
lock.notifyAll();
if (currentNum == MAX_NUM) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
@Override
public void run() {
product();
}
}
static class Consumer implements Runnable {
public void consume() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock) {
if (currentNum == MIN_NUM) {
lock.notifyAll