官网地址

程序猿升级课

热爱开源,喜欢摸索


并行模式之生产者消费者

原理

生产者-消费者模式是一个经典的多线程设计模式,它为多线程的协作提供了良好的解决方案。在生产者-消费者模式中,通常有两类线程,即若干个生产者线程和若干个消费者线程。生产者线程负责提交用户请求,消费者线程负责处理用户请求。生产者和消费者之间通过共享内存缓冲区进行通信。

生产者和消费者分开,互相不用关系

学到的只是启蒙思想,如何使用,就看大家了

实现

  • 定义一个队列

  • 生产者和消费者都对该队列操作

    生产者添加内容,消费者获取内容

    逻辑:当消费完了,就等待。当添加了就唤醒,消费者

生产者-消费者模式是一个经典的多线程设计模式,它为多线程的协作提供了良好的解决方案。在生产者-消费者模式中,通常有两类线程,即若干个生产者线程和若干个消费者线程。生产者线程负责提交用户请求,消费者线程负责处理用户请求。生产者和消费者之间通过共享内存缓冲区进行通信。

消费者

/**
* @Package: com.consumer
* @Description:从队列中获取参数
* @author: liuxin
* @date: 2017/7/11 下午5:20
*/
public class Consumer implements Runnable {
   Container container;

   Consumer(Container container) {
       this.container = container;
   }

   public void run() {
       for(int i=1; i<20; i++) { //一共要吃20个
           try { //生成一个睡1秒,便于观察
               Thread.sleep((long) (Math.random() * 2000));
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
           System.out.println("消费了:" + container.pop());
       }
   }
}

生产者


/**
* @Package: com.consumer
* @Description: 添加资料
* @author: liuxin
* @date: 2017/7/11 下午5:18
*/
public class Product implements Runnable {
   Container container;

   Product(Container container) {
       this.container = container;
   }

   public void run() {
       for (int i = 1; i < 20; i++) { //一共要生成20个
           String wt = i + "馒头";
           container.push(wt);
           System.out.println("生产了:" + wt);
           try { //生成一个睡1秒,便于观察
               Thread.sleep((long) (Math.random() * 1000));
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
   }
}


测试

public class Main {
   public static void main(String[] args) {

       //创建队列,队列中只能装5个
       Container container = new Container();

       Product product = new Product(container);

       Consumer consumer = new Consumer(container);

       new Thread(product).start();
       new Thread(consumer).start();
   }
}
public class Container {
   private Queue<String> queue = new ConcurrentLinkedQueue<String>();

   /**
    * 添加参数,当已经满了了, 当前线程就等待,等到消费者去消费。
    *
    * @param message
    */
   public synchronized void push(String message) {
       while (queue.size() == 5) {
           try {
               this.wait(); //阻塞生产者
               System.out.println("已经装满了");
           } catch (Exception e) {
               e.printStackTrace();
           }
       }
       this.notify();
       queue.add(message);
   }

   /**
    * 当已经消费完了,就等待,然后唤醒生产者去消=
    * iooooouihyzAS
    * @return
    */
   public synchronized String pop() {
       //当容器中没有了,就等待
       while (queue.size() == 0) {
           try {
               this.wait();
           } catch (Exception e) {
               e.printStackTrace();
           }
       }
       this.notify();//唤醒生产者
       return queue.poll();
   }

}

posted @ 2017-07-15 22:53  chinesszz  阅读(231)  评论(0编辑  收藏  举报
ヾ(≧O≦)〃嗷~