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

    技术2024-10-14  76

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

     

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

    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(); }}

     

     

     

     

     

     

    最新回复(0)