JAVA中synchronized与wait、notify的使用

JAVA中synchronized与wait、notify的使用

代码目的:由两个线程分别控制PrintMessages 类中成员变量的赋值和打印,并交替打印出“熊大”+“男”和“xionger”+“nv”。
本文属于对synchronized(resource)和wait、notify的练习。
其中:wait、notify方法必须在synchronized(resource)大括号内使用,因为需要锁对象来调用wait、notify方法。如resource.wait()和resource.notify()。
同时若需使两个线程交替运行,还需加一个标志位flag来确保线程的交替运行。

首先添加两个继承Runnable接口的类

//赋值线程
public class ThreadInput implements Runnable{
 PrintMessages r;
  public ThreadInput(PrintMessages r){
  this.r=r;
 }
  @Override
 public void run() {
  int i =0;
  while(true){
   synchronized (r) { //共享一个锁对象r,即mian方法传到构造中的引用对象。
   if(!r.flag) {
       try {
     r.wait();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   if(i%2==0){
    r.name="熊大";
    r.sex ="男";
  
   }else{
    r.name="xionger";
    r.sex ="nv";   
   }
   i++;
   r.flag=false;
   r.notifyAll();
       }
      }
  
 }
//打印线程
public class TheadOutput implements Runnable {
PrintMessages r;
public TheadOutput(PrintMessages r){
  this.r=r;
 }
public void run() {
while(true)
{ 
  synchronized(r) {
  if(r.flag==true)
   {
   try{r.wait();}catch(Exception e){};
  }
    //交替打印熊大 男 xionger nv
  System.out.println(r.name+"....."+r.sex);
  r.flag=true;
  r.notifyAll();    
  //此时可以用notify也可以用notifyAll,notify为随机唤醒一个休眠线程。
  //notifyall是唤醒所有线程。因为此时除主线程外总共两个线程,所以没关系。
  
    }
  }
 }
}
}
//添加类,里面包含拥有成员name 和 sex以及flag
public class PrintMessages {
 public String name;
 public String sex;
 public boolean flag=true;
 }
//实现代码
public class ThreadCommunicationDemo {
 public static void main(String[] args) {
   PrintMessages r =new PrintMessages();
  Runnable a =new ThreadInput(r);    
  Runnable b =new TheadOutput(r);    //注意两个实现类共用一个对象r。
  Thread c =new Thread(a);
  Thread d =new Thread(b);
  c.start();
  d.start();
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值