等待唤醒机制 (同步锁中使各个线程能有效的利用资源)
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 无效监视器异常
}
}