生产者消费者模型

一. Synchronized+wait()+notify()

1)生产者

class Producer extends Thread{
    private Buffer buffer;

    public Producer(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                buffer.add(i);
                System.out.println("生产者生产的数据:" + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

2)消费者

class Consumer extends Thread{
    private Buffer buffer;

    public Consumer(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            int val = 0;
            try {
                val = buffer.pull();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("消费者消费的数据: " + val);
        }
    }
}

3)缓存区

class Buffer{
    private Queue<Integer> queue = new LinkedList<>();
    private int size = 5;

    public synchronized int pull() throws InterruptedException {
        if (queue.size() == 0){
        	System.out.println("池子空了没法消费,等待生产者生产。。。");
            wait();
        }
        int val = queue.poll();
        notify();               // 通知生产者生产
        return val;
    }

    public synchronized void add(int val) throws InterruptedException {
        if (queue.size() > size){
        	System.out.println("池子满了,等待消费者消费。。。");
            wait();                 // 阻塞生产者生产
        }
        queue.add(val);
        notify();       // 通知消费者去消费
    }
}

4)测试

public class ProducerAndConsumerDemo {
    public static void main(String[] args) {
        Buffer buffer = new Buffer();
        Producer producer = new Producer(buffer);
        Consumer consumer = new Consumer(buffer);
        producer.start();
        consumer.start();
    }
}

二、Lock+await()+signal

1)生产者

class ProducerV2 extends Thread{
    private BufferPool bufferPool;

    public ProducerV2(BufferPool bufferPool) {
        this.bufferPool = bufferPool;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                bufferPool.increment(i);
                System.out.println(Thread.currentThread().getName()+"生产了一个数据");
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

2)消费者

class ConsumerV2 extends Thread{
    private BufferPool bufferPool;

    public ConsumerV2(BufferPool bufferPool) {
        this.bufferPool = bufferPool;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                bufferPool.decrement();
                System.out.println(Thread.currentThread().getName()+"消费了一个数据");
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

3)缓存池

class BufferPool {
    private Queue<Integer> queue = new LinkedList<>();
    private int size = 5;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    /**
     * 生产数据
     */
    public void increment(int val){
        lock.lock();        // 生产时锁住池子
        try {
            while (queue.size() == size) {                // 池子数据满了,不能生产
                condition.await();
            }
            queue.add(val);                           // 池子未满,可以生产
            condition.signalAll();              // 通知消费者来消费
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();                      // 解锁
        }

    }
    /**
     * 消费数据
     */
    public void decrement(){
        lock.lock();                // 消费的时候上锁
        try {
            while (queue.size() == 0) {                // 池子里没有数据,不能消费
                condition.await();
            }
            queue.poll();                           // 池子空,可以生产
            condition.signalAll();              // 通知消费者来消费
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();                      // 解锁
        }
    }
}

4)测试

public class ProducerConsumerDemo{

    public static void main(String[] args) {
        BufferPool bufferPool = new BufferPool();
        ProducerV2 producer = new ProducerV2(bufferPool);
        ConsumerV2 consumer = new ConsumerV2(bufferPool);
        producer.start();
        consumer.start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值