java线程 反复唤醒_Java 多线程之 等待唤醒机制

等待唤醒机制 (同步锁中使各个线程能有效的利用资源)

public class Resource { //锁类

public String name;

public int age;

public boolean flag=false;//标记true赋值完成  ,false输出完成

}

public class Input implements Runnable{ //输入任务类

private Resource r;

public Input(){}

public Input(Resource r){ this.r=r; } //有参构造

public void run() {

int i=0;

while(true){ //复制完(true)等  输出完(false)赋值

synchronized (r){ //同步代码块(锁对象)

if(r.flag){ r.wait();//点try...catch } //锁.等待(线程暂停)

if(i%2==0){ r.name="张三";  r.age=18; }//没改完就获取了

else{ r.name="李四";  r.age=19; }

r.flag=true;

r.notify(); //锁.唤醒(随机唤一锁)

} //r.notifyAll(); 唤醒线程池中所有wait() 线程

i++;

}

}

}

public class Output implements Runnable{ //输出任务类

private Resource r;

public Output(){}

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

public void run() {

//对Resource进行输出

while(true){

synchronized(r){

if(!r.flag){ r.wait();//点try...catch }

System.out.println(r.name+"..."+r.age);

r.flag=false;

r.notify();

}

}

}

}

public class TestResource {//等待唤醒机制

public static void main(String[] args) {

Resource r=new Resource(); //锁

Input in=new Input(r); //任务共用一把锁

Output out=new Output(r);

Thread t1=new Thread(in);

Thread t2=new Thread(out);

t1.start();

t2.start();//IllegalMonitorStateException  无效监视器异常

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值