Java多线程生产者与消费者模型(分别使用synchronized和重入锁实现)

synchronized实现:

消费者:

public class ConsumerThread implements Runnable {
    private Goods goods;
    @Override
    public void run() {
        //消费者
        while(true){
            //厂库不空则消费
            synchronized (ThreadDemo.queue) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (!ThreadDemo.queue.isEmpty()) {
                    ThreadDemo.queue.poll();
                    System.out.println(Thread.currentThread().getName()+"消费商品,商品数量:"+ThreadDemo.queue.size());
                } else {
                    //唤醒在ThreadDemo.queue对象上调用wait()阻塞的线程,使其进入可以竞争锁的状态
                    ThreadDemo.queue.notifyAll();
                }
            }
        }
    }
}

生产者:

public class ProducerThread implements Runnable {
    private Goods goods;
    @Override
    public void run() {
        //生产者
        while(true){
            //厂库没满则生产
            synchronized (ThreadDemo.queue) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                goods=new Goods(1,"商品");
                if (ThreadDemo.queue.size()<ThreadDemo.MAX_POOL) {
                    ThreadDemo.queue.add(goods);
                    System.out.println(Thread.currentThread().getName()+"生产商品,商品数量:"+ThreadDemo.queue.size());

                } else {
                    try {
                        //在ThreadDemo.queue对象上调用wait()方法,阻塞当前线程,同时会释放同步锁
                        ThreadDemo.queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

Goods类:

public class Goods {
    private int id;
    private String name;

    public Goods(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

主程序:

public class ThreadDemo {
    //厂库大小
    public static final int MAX_POOL=5;
    //生产者数量
    public static final int MAX_PRODUCER=3;
    //消费者数量
    public static final int MAX_CONSUMER=3;
    //存储的队列
    public static Queue<Goods> queue=new ArrayBlockingQueue<>(MAX_POOL);
    public static void main(String[] args) {
        ProducerThread producer=new ProducerThread();
        ConsumerThread consumer=new ConsumerThread();
        for(int i=0;i<MAX_PRODUCER;i++) {
            Thread threadA = new Thread(producer, "生产者线程"+i);
            threadA.start();
        }
        for(int j=0;j<MAX_CONSUMER;j++) {
            Thread threadB = new Thread(consumer, "消费者线程"+j);
            threadB.start();
        }
    }
}

重入锁实现:

消费者:

public class ConsumerThreadLock implements Runnable {

    private Goods goods;
    Lock lock;
    private Condition goodsCondition;

    public ConsumerThreadLock(Lock lock,Condition goodsCondition){
        this.lock = lock;
        this.goodsCondition = goodsCondition;
    }

    @Override
    public void run() {
        //消费者
        while(true){
            //厂库不空则消费
            lock.lock();
                try {
                    Thread.sleep(500);
                    if (!ThreadDemo.queue.isEmpty()) {
                        ThreadDemo.queue.poll();
                        System.out.println(Thread.currentThread().getName()+"消费商品,商品数量:"+ThreadDemo.queue.size());
                    } else {
                        //唤醒在ThreadDemo.queue对象上调用wait()阻塞的线程,使其进入可以竞争锁的状态
                        goodsCondition.signalAll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally{
                    lock.unlock();
                }
        }
    }
}

生产者:

public class ProducerThreadLock implements Runnable {
    private Goods goods;
    private Lock lock;
    private Condition goodsCondition;

    public ProducerThreadLock(Lock lock,Condition goodsCondition){
        this.lock = lock;
        this.goodsCondition = goodsCondition;
    }

    @Override
    public void run() {
        //生产者
        while(true){
            //厂库没满则生产
            lock.lock();
                try {
                    Thread.sleep(500);
                    goods=new Goods(1,"商品");
                    if (ThreadDemo.queue.size()<ThreadDemo.MAX_POOL) {
                        ThreadDemo.queue.add(goods);
                        System.out.println(Thread.currentThread().getName()+"生产商品,商品数量:"+ThreadDemo.queue.size());

                    } else {
                        try {
                            //在ThreadDemo.queue对象上调用wait()方法,阻塞当前线程,同时会释放同步锁
                            goodsCondition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally{
                    lock.unlock();
                }
        }
    }
}

主程序:

public class LockDemo {
    //厂库大小
    public static final int MAX_POOL=5;
    //生产者数量
    public static final int MAX_PRODUCER=3;
    //消费者数量
    public static final int MAX_CONSUMER=3;
    //存储的队列
    public static Queue<Goods> queue=new ArrayBlockingQueue<>(MAX_POOL);
    public static void main(String[] args) {
        //创建锁
        Lock lock = new ReentrantLock();
        //创建当前锁的条件对象
        Condition goodsCondition = lock.newCondition();
        ProducerThreadLock producer=new ProducerThreadLock(lock,goodsCondition);
        ConsumerThreadLock consumer=new ConsumerThreadLock(lock,goodsCondition);
        for(int i=0;i<MAX_PRODUCER;i++) {
            Thread threadA = new Thread(producer, "生产者线程"+i);
            threadA.start();
        }
        for(int j=0;j<MAX_CONSUMER;j++) {
            Thread threadB = new Thread(consumer, "消费者线程"+j);
            threadB.start();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值