线程通信notify(),wait()

public class ResourceDemo
{
public static void main(String args[]){
Resource r = new Resource();
Input input = new Input(r);
Output output = new Output(r);
Thread t1 = new Thread(input);
Thread t2 = new Thread(output);
t1.start();
t2.start();
}
}


class Resource{
String name;
String sex;
boolean flag = true;
}


class Input implements Runnable
{
private Resource r;

public Input(Resource r){
this.r = r;
}

public void run(){
int num = 0;
while(true){
synchronized(r){
if(!r.flag){
try{
System.out.println("input wait");
r.wait();//看r这个锁开了没有,开了就继续往下执行并占有r这个锁
System.out.println("input wait over");
}catch(Exception e){

}
}
if(num==0){
System.out.println("input lili");
r.name = "LiLi";
r.sex = "girl";
}else{
System.out.println("input DanDan");
r.name = "DanDan";
r.sex = "boy";
}
num = (num+1)%2;
try{
r.flag = false;
System.out.println("input notify");
r.notify();
}catch(Exception e){

}
}
}
}
}




class Output implements Runnable
{


private Resource r;

public Output(Resource r){
this.r = r;
}

public void run(){
while(true){
try{
System.out.println("sleep");
Thread.sleep(2000);
}catch(Exception e){

}
synchronized(r){
if(r.flag){
try{
System.out.println("output wait");
r.wait();
System.out.println("output wait over");
}catch(Exception e){

}
}
System.out.println(r.name+"--"+r.sex);
try{
r.flag = true;
//notify使wait线程变为阻塞
r.notify();//等notify所处的线程结束之后r这个锁才打开,其他r锁下的线程才执行
System.out.println("pre output notify");
Thread.sleep(2000);
System.out.println("end output notify");
}catch(Exception e){

}
}
}

}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值