当前位置: 移动技术网 > IT编程>开发语言>Java > Java并发编程中的生产者与消费者模型简述

Java并发编程中的生产者与消费者模型简述

2019年07月22日  | 移动技术网IT编程  | 我要评论

综艺资讯,tuanbao,都市异能之非凡人生

概述
对于多线程程序来说,生产者和消费者模型是非常经典的模型。更加准确的说,应该叫“生产者-消费者-仓库模型”。离开了仓库,生产者、消费者就缺少了共用的存储空间,也就不存在并非协作的问题了。

示例
定义一个场景。一个仓库只允许存放10件商品,生产者每次可以向其中放入一个商品,消费者可以每次从其中取出一个商品。同时,需要注意以下4点:
1.  同一时间内只能有一个生产者生产,生产方法需要加锁synchronized。
2.  同一时间内只能有一个消费者消费,消费方法需要加锁synchronized。
3.  仓库为空时,消费者不能继续消费。消费者消费前需要循环判断当前仓库状态是否为空,空的话则消费线程需要wait,释放锁允许其他同步方法执行。
4.  仓库为满时,生产者不能继续生产,生产者生产钱需要循环判断当前仓库状态是否为满,满的话则生产线程需要wait,释放锁允许其他同步方法执行。

示例代码如下:

  

 public class concurrence { 
    public static void main(string[] args) { 
      warehouse warehouse = new warehouse(); 
      producer producer = new producer(warehouse); 
      consumer consumer = new consumer(warehouse); 
   
      new thread(producer).start(); 
      new thread(consumer).start(); 
    } 
  } 
   
  class warehouse { 
    private static final int store_size = 10; 
    private string[] storeproducts = new string[store_size]; 
    private int index = 0; 
   
    public void pushproduct(string product) { 
      synchronized (this) { 
        while (index == store_size) { 
          try { 
            this.wait(); 
          } catch (interruptedexception e) { 
            e.printstacktrace(); 
          } 
        } 
   
        storeproducts[index++] = product; 
        this.notify(); 
   
        system.out.println("生产了: " + product + " , 目前仓库里共: " + index 
            + " 个货物"); 
      } 
    } 
   
    public synchronized string getproduct() { 
      synchronized (this) { 
        while (index == 0) { 
          try { 
            this.wait(); 
          } catch (interruptedexception e) { 
            e.printstacktrace(); 
          } 
        } 
   
        string product = storeproducts[index - 1]; 
        index--; 
        system.out.println("消费了: " + product + ", 目前仓库里共: " + index 
            + " 个货物"); 
        this.notify(); 
        return product; 
      } 
    } 
  } 
   
  class producer implements runnable { 
    warehouse warehouse; 
   
    public producer(warehouse wh) { 
      this.warehouse = wh; 
    } 
   
    @override 
    public void run() { 
      for (int i = 0; i < 40; i++) { 
        string product = "product" + i; 
        this.warehouse.pushproduct(product); 
      } 
    } 
  } 
   
  class consumer implements runnable { 
    warehouse warehouse; 
   
    public consumer(warehouse wh) { 
      this.warehouse = wh; 
    } 
   
    @override 
    public void run() { 
      for (int i = 0; i < 40; i++) { 
        this.warehouse.getproduct(); 
      } 
    } 
  } 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网