Dict.CN 在线词典, 英语学习, 在线翻译 ------------- MyGitee 朱秋贵内科诊所 My腾云code

多线程 input生产 res(username,sex) out消费 synchronized(res) wait-notify

1、wait 使用说明

 

public class Thread001 {


class Res{
public String userName;
private char sex;
private boolean flag;
}

 

 

class InputThread extends Thread{

Res res;

public InputThread(Res res) {
this.res=res;
}

 

@Override
public void run() {
int count=0;
while (true){
  synchronized (res){
    try {
      if(res.flag)//true
      {
        res.wait();
      }
      }catch (Exception e){

    }
    if(count==0){
      res.userName="胜军";
      res.sex='男';
    }else {
      res.userName="小君";
      res.sex='女';
    }
    res.flag=true;
    //唤醒消费者线程, 就绪状态被cpu调度为运行状态
    res.notify();
    count=(count+1)%2;
  }
 }
}

 

 

 


}

 

 

class OutThread extends Thread{
  Res res;
  public OutThread(Res res) {
    this.res=res;
  }

  @Override
  public void run() {
    while (true){
      synchronized (res){
        try {
          if(!res.flag){//flag=false
          //当线程变为阻载状态,同时释放锁
          res.wait();
        }
        }catch (Exception e){

        }


      System.out.println(res.userName+","+res.sex);
      res.flag=false;
      //唤醒写的线程
      res.notify();
    }
     }
  }

 

 

 


}

 


  public void start(){
    Res res=new Res();
    //写线程
    new InputThread(res).start();
    //读的线程
    new OutThread(res).start();
    //锁对象Res
  }


  public static void main(String[] args){
    new Thread001().start();
  }

 

 


}

 

 

 

 

 

 

 

 

posted @ 2021-04-06 10:32  cn2024  阅读(72)  评论(0编辑  收藏  举报