简单的生产者消费者

工作了这么长时间一直处理Javaweb方面的工作

涉及到Java基础的东西非常不全面

刚忙完手头的工作,打算熟悉下线程、锁等相关的东西,也一直在看大佬们的博客

希望新的一年能有较大的提升

 

下面这是一个简单的生产消费者模式

 

单个线程执行的时候没啥问题

多个生产者,多个消费者下会就开始一直在等待了,不生产,也不消费了

最后发现是那个 await方法位置错了,应该写到生产或者消费的前面

另外使用ReentrantLock不能使用wait和notify或者notifyAll,必须使用下面的方式

Condition condition = reentrantLock.newCondition();
condition.await();
condition.signal();

 

第一次写的工厂类有点问题,判断那块应该把if改为while循环,因为唤醒之后不会再去做判断,程序往下执行,可能会导致获取的数据为null,改为while循环,先判断条件再往下执行

(按理来说,访问的是同一个队列,生产完成后,才唤醒消费者消费,消费者唤醒后,队列里面应该是有值的,感觉锁还是有问题,同时多个线程进入了条件语句,前一个取完值,后一个从条件语句出来,再去取,导致值为空)

最新工厂类如下

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Factory{

    ReentrantLock reentrantLock = new ReentrantLock();
    Condition produceCondition = reentrantLock.newCondition();
    Condition getCondition = reentrantLock.newCondition();

    ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();

    public void produce(String userName,String str){
        System.out.println("生产者["+userName + "] 等待进入");
        reentrantLock.lock();
        System.out.println("生产者["+userName + "] 进来了");
        try{
            while(queue.peek() != null){
                System.out.println("生产者["+userName + "]在等待生产");
                produceCondition.await();
                System.out.println("生产者["+userName + "]开始生产");
            }
            queue.offer(str);
            System.out.println("生产者[" + userName +"] 生产了:" + str);
            getCondition.signal();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            System.out.println("生产者["+userName + "] 出去了");
            reentrantLock.unlock();
        }
    }

    public void get(String userName){
        System.out.println("消费者["+userName + "] 等待进入");
        reentrantLock.lock();
        System.out.println("消费者["+userName + "] 进来了");
        try{
            while (queue.peek() == null){
                System.out.println("消费者[" + userName +"] 在等待消费");
                getCondition.await();
                System.out.println("消费者[" + userName +"] 开始消费");
            }
//            Thread.sleep(1000);
            System.out.println("消费者[" + userName +"] 获得了:" +queue.poll());
            produceCondition.signal();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            System.out.println("消费者["+userName + "] 出去了");
            reentrantLock.unlock();
        }
    }

}

工厂类

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Factory{

    ReentrantLock reentrantLock = new ReentrantLock();
    Condition condition = reentrantLock.newCondition();

    Queue<String> queue = new ConcurrentLinkedQueue<>();

    public void produce(String userName,String str){
        System.out.println("生产者["+userName + "]等待进入");
        reentrantLock.lock();
        System.out.println("生产者["+userName + "]进来了");
        try{
            if(queue.peek() != null){
                System.out.println(userName + "在等待生产");
                condition.await();
            }
//            Thread.sleep(1000);
            queue.offer(str);
            System.out.println("生产者[" + userName +"]生产了:" + str);
            condition.signal();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            System.out.println("生产者["+userName + "]出去了");
            reentrantLock.unlock();
        }
    }

    public void get(String userName){
        System.out.println("消费者["+userName + "]等待进入");
        reentrantLock.lock();
        System.out.println("消费者["+userName + "]进来了");
        try{
            if(queue.peek() == null){
                System.out.println(userName + "在等待消费");
                condition.await();
            }
//                Thread.sleep(1000);
            System.out.println("消费者[" + userName +"] 获得了:" +queue.poll());
            condition.signal();

        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            System.out.println("消费者["+userName + "]出去了");
            reentrantLock.unlock();
        }
    }

}

生产者

public class Produce implements Runnable{

    Factory factory;
    String name;

    public Produce(Factory factory,String name) {
        this.factory = factory;
        this.name = name;
    }

    @Override
    public void run() {
        while (true){
            factory.produce(name,"product_" + System.currentTimeMillis());
        }
    }
}

消费者

public class Produce implements Runnable{

    Factory factory;
    String name;

    public Produce(Factory factory,String name) {
        this.factory = factory;
        this.name = name;
    }

    @Override
    public void run() {
        while (true){
            factory.produce(name,"product_" + System.currentTimeMillis());
        }
    }
}

测试代码

public class MainTest {

    public static void main(String[] args) {
        Factory factory = new Factory();
        Thread produce1 = new Thread(new Produce(factory,"生产者1"));
        Thread consumer1 = new Thread(new Consumer(factory,"消费者1"));
        Thread produce2 = new Thread(new Produce(factory,"生产者2"));
        Thread consumer2 = new Thread(new Consumer(factory,"消费者2"));
        Thread produce3 = new Thread(new Produce(factory,"生产者3"));
        Thread consumer3 = new Thread(new Consumer(factory,"消费者3"));
        produce1.start();
        consumer1.start();
        produce2.start();
        consumer2.start();
        produce3.start();
        consumer3.start();
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值