程序设计模型之生产消费模型

                顾名思义,生产消费模型中只有生产者生产了产品,消费者才能使用,那么消费者怎么判断生产者生产了,同时又怎么判断消费者使用了产品呢?

 

在程序中主要有两种实现方式:

1:轮训模型

     也就是说当生产者生产了产品,消费者每隔一段时间就过来看以下,如果生产了就取走。

2:等待/通知模型

      当生产者生产后就通知相应的消费者,由消费者获取生产者的产品。

 

比较:当使用轮训模型的时候比较简单,在一个while(true)循环当中每隔一段时间看下,但是当生产者很长时间都没有生产产品的时候这样就浪费了大量的系统资源,而当利用等待通知模型时则避免了这种情况。

 

等待通知模型源码:

 

Provider(生产者)

package Wait_Notify;

import java.util.List;

//生产线程
//消费者线程
public class Provider extends Thread{

 List StudentList;
 int count=0;
 public Provider(List StudentList){
  this.StudentList=StudentList;
 }
 
 
 public void run(){
  while(true){
   //未锁
   //锁定等待通知的对象
   synchronized(StudentList){
    try {
     Thread.sleep(1000);
    } catch (InterruptedException e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
    }
   
   if(StudentList.isEmpty()){
    Student one=new Student();
    one.id=count;
    one.Msg="生产者生产了";
    StudentList.add(one);
    System.out.println(count+"生产了");
    //发送生产消息
    count++;
    StudentList.notify();
   }
   else
   if(StudentList.size()!=0){
    //接受者没收到就等待
    try {
     StudentList.wait();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   
  }
   
  }
  
 }
 }
 

生产产品类型(Student)
 

//等待通知模型
public class Student {
 int id;
 String Msg;
 
 //重写toString
 public String toString(){
  
  return id+"-----"+Msg;
 }
 
}

 

 

customer消费者

 

import java.util.List;

//消费者线程
public class Custermer extends Thread{

 List StudentList;
 int count=0;
 public Custermer(List StudentList){
  this.StudentList=StudentList;
 }
 
 
 public void run(){
  while(true){
   //未锁
   
   synchronized(StudentList){

   if(StudentList.isEmpty()){
    //如果未生产等待
    try {
     StudentList.wait();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    
   }
  
   if(StudentList.size()!=0){
    //生产取出并打印
   Student speak=(Student) StudentList.get(0);
   
   System.out.println(speak.id+"接收了");
   StudentList.remove(0);
   //取出后通知
   StudentList.notify();
   }
 }
 
 }
  
 }
}

测试:

import java.util.List;

//测试运行
public class runTime {

 public static void main(String []args){
  List ShareList=new java.util.LinkedList();
  new Provider(ShareList).start();
  
  new Custermer(ShareList).start();
 }
}

 


 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值