Java-多线程的应用

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();
 }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值