`
feipigwang
  • 浏览: 746250 次
  • 性别: Icon_minigender_2
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

java多线程 生产者 消费者

 
阅读更多

/*
每一个对象除了有一个锁之外,还有一个等待队列(wait set),当一个对象刚创建的时候,它的对待队列是空的。
我们应该在当前线程锁住对象的锁后,去调用该对象的wait方法。

也就是在同步快 或者同步函数中调用  wait  对于生产者消费者问题应该在同一个对象的等待队列中

当调用对象的notify方法时,将从该对象的等待队列中删除一个任意选择的线程,这个线程将再次成为可运行的线程。
当调用对象的notifyAll方法时,将从该对象的等待队列中删除所有等待的线程,这些线程将成为可运行的线程。
wait和notify主要用于producer-consumer这种关系中。

 

下面模拟 生产者 消费者问题 
*/

class  Test  
{
 
 public static void main(String []args)
 {
  Queue q=new Queue();  //创建一个队列 
  Procedure p=new Procedure(q); //生产者线程
  Consumer c=new Consumer(q);//消费者线程
  p.start();  //启动
  c.start();//run 
 }
}


class  Procedure  extends Thread 
{
 Queue q;
 Procedure(Queue q)  //带参数构造函数 
 {
  this.q=q;
 }
 public  void run()
 {
  for(int i=0;i<100;i++)
  {
   q.put(i);  //向队列放数据
   System.out.println("Producer put "+i);  //显示队列数据
  }
  
  
 }

}

class  Consumer  extends Thread 
{
 Queue q;
 Consumer(Queue q)
 {
  this.q=q;  //构造函数
 }
 public  void run()  
 {
  while(true) 
  { 
   int n=q.get();  //从队列获取 数据
   try
      {
        Thread.sleep(10);  //线程等待一下
      }
  catch(Exception e)
   {
    
   }
   System.out.println("Consumer get"+ n);
  }
  
 }

}

class  Queue //面向对象的思想 用类封装数据
{
 int i ;// 队列数据 
 boolean bFull=false;
 public synchronized  int  get()   //同步方法 
 {
  if(bFull==false)
  { try
   {
    wait() ;// 使消费者线程等待  wait方法会跑出异常 使当前线程进入 this对象的等待序列  
    }
    catch(Exception e)
    {
     e.printStackTrace();
    }
  }
  bFull=false;  //如果有食物的话 设置食物为空 并且从this等待队列删除 线程 
  notify();//从this对象等待序列删除线程 
  return this.i; //返回i 
 }
 
 
 public  synchronized void put(int i)
 {
  if(!bFull) //如果为空
  {
   this.i=i; //放入数据
   bFull=true; //设置为TRUE 
   notify();//从等待队列删除线程  
  }
  try
  {
   wait();//如果食物不是空那么进入等待队列
  }
  catch(Exception e)
    {
     e.printStackTrace();
   }
 
     }
}


0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics