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  无效监视器异常

}

}

posted @ 2019-01-10 17:04  博客张C  阅读(376)  评论(0编辑  收藏  举报