Java常用三种方式解决生产者消费者问题(详细)

package test;

/**
 * Synchronized 版本解决生产者消费者
 * wait() / notify()方法 
 */
import java.util.LinkedList;
import java.util.Queue;

public class ProducerAndConsumerForSynchronized {
    // 1. 先定义最大生产长度
    private final int MAX_SIZE = 10;
    // 2.定义储存队列
    private Queue<Object> storeList = new LinkedList<Object>();

    // 3.定义生产者
    class Producer extends Thread {
        @Override
        public void run() {
            producer();
        }

        private void producer() {
            while (true) {
                synchronized (storeList) {
                    while (storeList.size() == MAX_SIZE) {
                        storeList.notify();
                        System.out.println("当前库存数量达到最大值:" + MAX_SIZE + "条");
                        try {
                            // 暂停生产
                            storeList.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    storeList.add(new Object());
                    storeList.notify();
                    System.out.println("生产者产量增加一条,库存" + storeList.size());
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    // 4.定义消費者
    class Consumer extends Thread {
        @Override
        public void run() {
            consumer();
        }

        private void consumer() {
            while (true) {
                synchronized (storeList) {
                    while (storeList.size() == 0) {
                        storeList.notify();
                        System.out.println("当前库存为空");
                        try {
                            // 暂停消费
                            storeList.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    storeList.poll();
                    storeList.notify();
                    System.out.println("消费者消费一条产量,当前库存为" + storeList.size());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        ProducerAndConsumerForSynchronized pc = new ProducerAndConsumerForSynchronized();
        Producer producer = pc.new Producer();
        Consumer consumer = pc.new Consumer();
        producer.start();
        consumer.start();
    }
}
 

 

package test;

/**
 * Lock 版本解决生产者消费者
 * await() / signal()方法 
 */
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerAndConsumerForLock {
    // 1. 先定义最大生产长度
    private final int MAX_SIZE = 10;
    // 2.定义储存队列
    private Queue<Object> storeList = new LinkedList<Object>();
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    class Producer extends Thread {
        @Override
        public void run() {
            producer();
        }

        private void producer() {
            while (true) {
                lock.lock();
                try {
                    while (storeList.size() == MAX_SIZE) {
                        System.out.println("当前库存满");
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    storeList.add(1);
                    condition.signal();
                    System.out.println("生产者产量增加一条,库存" + storeList.size());
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    class Consumer extends Thread {
        @Override
        public void run() {
            consumer();
        }

        private void consumer() {
            while (true) {
                lock.lock();
                try {
                    while (storeList.size() == 0) {
                        System.out.println("当前库存为空");
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    storeList.poll();
                    condition.signal();
                    System.out.println("消费者消费一条任务,当前队列长度为" + storeList.size());
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) {
        ProducerAndConsumerForLock pc = new ProducerAndConsumerForLock();
        Producer producer = pc.new Producer();
        Consumer consumer = pc.new Consumer();
        producer.start();
        consumer.start();
    }
}
 

package test;

/**
 * BlockingQueue阻塞队列版本解决生产者消费者
 * put() / take() 方法
 */
import java.util.concurrent.LinkedBlockingQueue;

public class ProducerAndConsumerForBlockingQueue {
    // 定义储存队列
    private LinkedBlockingQueue<Object> storeList = new LinkedBlockingQueue<>(10);

    class Producer extends Thread {
        @Override
        public void run() {
            produce();
        }

        public void produce() {
            while (true) {
                try {
                    storeList.put(new Object());
                    System.out.println("生产者生产了一个商品 ,库存:" + storeList.size());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    class Consumer extends Thread {
        @Override
        public void run() {
            consume();
        }

        public void consume() {
            while (true) {
                try {
                    storeList.take();
                    System.out.println("消费者消费了一个商品 ,库存:" + storeList.size());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        ProducerAndConsumerForBlockingQueue pc = new ProducerAndConsumerForBlockingQueue();
        Producer producer = pc.new Producer();
        Consumer consumer = pc.new Consumer();
        producer.start();
        consumer.start();
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值