Java-多线程的应用

来源:互联网 发布:club monaco淘宝 编辑:程序博客网 时间:2024/05/17 23:11
class Info    //主信息类
{
 private String name="Aaron";
 private String content="Ghost";
 private boolean flag=false;  //设置标志位
 public void setname(String name)
 {
  this.name=name;
 }
 public String getname()
 {
  return this.name;
 }
 public void setcontent(String content)
 {
  this.content=content;
 }
 public String getcontent()
 {
  return this.content;
 }
 public synchronized void set(String name,String content)
 {
  if(!flag)
  {
   try
   {
    super.wait();//等待消费者取出
   }catch(InterruptedException e)
   {
    e.printStackTrace();
   }
  }
  this.setname(name);
  try{
   Thread.sleep(300);
  }catch(InterruptedException e)
  {
   e.printStackTrace();
  }
  this.setcontent(content);
  flag=false;//重置标志位,表示可以取走
  super.notify();//唤醒等待线程
 }
 public synchronized void get()
 {
  if(flag)
  {
   try
   {
    super.wait();
   }catch(InterruptedException e)
   {
    e.printStackTrace();
   }
  }
  try{
   Thread.sleep(90);
  }catch(InterruptedException e)
  {
   e.printStackTrace();
  }
  System.out.println("姓名:"+this.getname()+"内容:"+this.getcontent());
  flag=true;  //修改标志位,表示可以恢复生产
  super.notify(); //唤醒等待线程
 }
}
class producer implements Runnable
{
 private Info info=null;
 public producer(Info info)
 {
  this.info=info;
 }
 public void run()     //run方法的覆写
 {
  boolean flag=false;
  for(int i=0;i<20;i++)
  {
  if(flag)
  {
   this.info.set("Aaron", "Ghost");
   flag=false;
  }
  else
  {
   this.info.set("husiyun", "goal");
   flag=true;
  }
  }
 }
}
class consumer implements Runnable
{
 private Info info=null;
 public consumer(Info info)
 {
  this.info=info;
 }
 public void run()      //run方法的覆写
 {
  for(int i=0;i<20;i++)
  {
   try
   {
    Thread.sleep(100);
   }catch(InterruptedException e)
   {
    e.printStackTrace();
   }
   this.info.get();
  }
 }
}
public class test70 {
 public static void main(String args[])
 {
  Info i=new Info();   //先实例化
  producer pro=new producer(i);
  consumer con=new consumer(i);
  new Thread(pro).start();
  new Thread(con).start();
 }
}
原创粉丝点击