java多线程经典案例之生产者和消费者模型
在java基础中生产者和消费者的案例是不可避免的一个经典问题 要想实现这个经典的案例我们要先了解实现它需要一些什么东西 1.容器:用于存放生产者生产的产品,消费者从中消费商品 2.生产者:不断生产商品,直到容器满了,停止生产。 3.消费者:不断消耗商品,直至容量里的商品为空,停止消费。 4锁:生产者和消费者向容器里添加和删除元素的时候可以同步进行 我们来看实现代码
package P_and_C; /** * Created by Lei on 2020/11/3 9:39 */ import java.util.LinkedList; import java.util.Queue; public class ProducerConsumerAppMain { //定义一个最大值和一个最小值当生产者达到最大值的时候线程等待 //定义一个最小值当消费者达到最小值的时候线程等待 private final int MAX_LEN=6; private final int MIN_SIZE=0; private Queue<Integer> queue = new LinkedList<Integer>(); //定义内部类Producer继承Thread class Producer extends Thread{ //实现run方法 @Override public void run(){ //调用produce方法 produce(); } //定义produce方法的实现 public void produce(){ while (true) { synchronized (queue){ while (queue.size()==MAX_LEN){ queue.notify(); System.out.println("生产队列已满"); try { queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //向队顶添加一个元素 queue.add(1); queue.notify(); System.out.println("生产者生产一条任务,当前队列长度为" + queue.size()); try { //睡眠0.5秒 Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } } //定义内类consumer class Consumer extends Thread{ //实现run方法 @Override public void run(){ consume(); } //定义consume方法的实现 public void consume(){ while (true){ synchronized (queue){ while (queue.size() ==MIN_SIZE){ queue.notify(); System.out.println("当前队列为空"); try { queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //推出一个元素 queue.poll(); queue.notify(); System.out.println("消费者消费一条任务,当前队列长度为" + queue.size()); try { sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } } public static void main(String[] args) { ProducerConsumerAppMain pc = new ProducerConsumerAppMain(); Producer p = pc.new Producer(); Consumer c = pc.new Consumer(); p.start(); c.start(); } }
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
年前无情被裁,我面试大厂的这几个月…