详解生产者消费者问题 lock newCondition的方法 附加代码 和遇到的问题详解

这里用到了Lock锁机制,newCondition能为多个线程提供不同的condition,详情见代码,特定的condition能唤醒特定的线程。相比synchronized同步方法的notifyAll,多了多个等待队列,notifyAll所有的线程都会唤醒,notify只能唤醒一个线程,有可能生产者线程唤醒的是生产者线程。对于condition来说,我们将其分成生产者线程和消费者线程,在生产者线程中唤醒消费者线程。
后面再写代码的过程中遇到了一个问题,解决方法看下面
这是第一版的代码:

public class Main {
    public static void main(String[] args) {
        Buffer buffer = new Buffer(5);
        Produce produce = new Produce(buffer);
        Consumer consumer = new Consumer(buffer);
        for (int i = 0; i < 5; i++) {
            new Thread(produce).start();
        }
        for (int i = 0; i < 1; i++) {
            new Thread(consumer).start();
        }

    }
}

class Buffer {
    private ArrayList<String> string;
    private int size;
    private Lock lock = new ReentrantLock();
    private Condition produceTh = lock.newCondition();
    private Condition consumerTh = lock.newCondition();
    public Buffer(int size) {
        this.size = size;
        string = new ArrayList<>();
    }
    public void put() throws InterruptedException {
        //产品生产入队列
        try {
            lock.lock();
            if (string.size() == size){
                System.out.println(Thread.currentThread().getName() + " await");
                produceTh.await();
            }
            Thread.sleep(300);
            string.add("产品");
            System.out.println(Thread.currentThread().getName() +" put:"+ string.size());
            consumerTh.signal();
        } finally {
            lock.unlock();
        }
    }

    public void take() throws InterruptedException {
        //拿走产品
        try {
            lock.lock();
            if (string.size() <= 0){
                consumerTh.await();
            }
            Thread.sleep(300);
            string.remove(string.size() -1);
            System.out.println(Thread.currentThread().getName() + " take:" + string.size());
            produceTh.signal();
        } finally {
            lock.unlock();
        }

    }
}

class Produce implements Runnable{
    Buffer buffer;

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

    @Override
    public void run() {
        while (true){
            try {
            
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值