黑马程序员——Java---多线程-生产者和消费者

来源:互联网 发布:淘宝付费流量 编辑:程序博客网 时间:2024/06/06 13:11
------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

/*两个实现Runnble接口的类,一个是生产者 maker ,一个是消费者 consumer ,分别覆盖了Runnable的run方法,创建线程的运行代码

生产者每生产一个产品就在控制台里面打印出来,然后停止1秒钟。

生产者每生产一个产品消费者就消费一个产品 然后在控制台里面打印出来。

生产者停止不生产的时候,消费者就一直等待生产者下一次生产,等待产品出来并消费掉将其打印在控制台。

控制台  输出信息 :

生产者生产 :haha-1
消费者消费 :haha-1
生产者生产 :haha-2
消费者消费 :haha-2
..................


利用懒汉式双判断同步的方式每次调用都返回同一个对象 的类  GetRes ,

res资源类,有设置和获取资源的同步方法 ,因为该类调用了 synchronized同步锁的方法,而该方法被多个线程调用的时候锁必须是同一个锁对象,才能保证变量的安全性,所

以就有了下面的懒汉式双判断同步的类,该类在整个程序中,只创建了一次对象,保证了对象的唯一性,从而使synchronized同步锁更加安全
*/

class res
{
 private String name;
 private int id=0;
 private boolean flg=false;
 synchronized void  set(String name,int id)
 {
  while(flg)
  {
   try{
    this.wait();
   }
   catch(InterruptedException e){
    
   }
  }
  try{
   Thread.currentThread().sleep(1000);
  }
  catch(InterruptedException e)
  {
   e.printStackTrace();
  }
  this.name=name;
  this.id+=id;
  System.out.println("生产者生产 :"+this.name+"-"+this.id);
  flg=true;
  this.notifyAll();
 }
 synchronized String get()
 {
  while(!flg)
  {
   try{
    this.wait();
   }
   catch(InterruptedException e){
    
   }
  }
  System.out.println("消费者消费 :"+this.name+"-"+this.id);
  flg=false;
  this.notifyAll();
  return null;
 }
}
class GetRes
{
 static private res s;
 res GetRes()
 {
  if(s==null)
  {
   synchronized(res.class)
   {
    if(s==null)
     s = new res();
   }
  }
  return s;
 }
}
class maker implements Runnable
{
 private res s=new GetRes().GetRes();
 public void run()
 {
  while(true)
  s.set("haha", 1);
 }
}
class consumer implements Runnable
{
 private res s=new GetRes().GetRes();
 public void run()
 {
  while(true)
  s.get();
  
 }
}
class test3
{
 static double timestacks=System.currentTimeMillis();
 public static void main(String[] args)
 {
  
  new Thread(new maker()).start();
  new Thread(new consumer()).start();
  new Thread(new maker()).start();
  new Thread(new consumer()).start();
  new Thread(new maker()).start();
  new Thread(new consumer()).start();
 }
}








0 0
原创粉丝点击