黑马程序员——线程间通信_等待唤醒机制

来源:互联网 发布:如何卖照片知乎 编辑:程序博客网 时间:2024/05/18 01:43

 

                                          ----------------------    android培训    java培训   期待与您交流!    ----------------------   
                      

package thread;
/**
 * 线程间通信:多个线程共享一个资源
 * 等待唤醒机制:wait(),notify()
 * @author wjw
 *
 */
public class Thread_Translate {
 public static void main(String[] args) {
  Res r=new Res();
  Thread_in in=new Thread_in(r);
  Thread_out out=new Thread_out(r);
  new Thread(in).start();
  new Thread(out).start();
 }
}
/*
 * 线程A  录入资源操作
 */
class Thread_in implements Runnable{
 public Thread_in(Res r){
  this.r=r;
 }
 private Res r;
 boolean boo=true;
 public void run(){
  while(true){
   synchronized(r){
    if(r.isBoo()){
     try{
      r.wait();//等待
     }catch(Exception e){
      e.printStackTrace();
     }
    }
    if(boo){
     r.setName("jack");
     r.setSex("man");
     boo=false;
    }else{
     r.setName("李经理");
     r.setSex("女女女女女女女女女"); 
     boo=true;
    }
    r.setBoo(true);
    r.notify();//唤醒
   }
   
  }
 }
}
/*
 * 线程 B  取出资源操作
 */
class Thread_out implements Runnable{
 public Thread_out(Res r){
  this.r=r;
 }
 private Res r;
 public void run(){
  while(true){
   synchronized(r){
    if(!r.isBoo()){
     try{
      r.wait();//等待
     }catch(Exception e){
      e.printStackTrace();
     }
    }
    System.out.println("name:"+r.getName()+",sex:"+r.getSex());
    r.setBoo(false);
    r.notify();//唤醒
   }
  }
 }
}
/*
 * 共享的资源
 */
class Res{
 private String name;
 private String sex;
 private boolean boo;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getSex() {
  return sex;
 }
 public void setSex(String sex) {
  this.sex = sex;
 }
 public boolean isBoo() {
  return boo;
 }
 public void setBoo(boolean boo) {
  this.boo = boo;
 }
 
}

 

 

 

                                          ----------------------    android培训    java培训   期待与您交流!    ----------------------   
                         详细请查看      http://edu.csdn.net/heima

 

原创粉丝点击