class Resource{
//属性进行私有化,对外提供get方法
private String name;
private String sex;
private boolean flag = false;
public synchronized void set(String name,String sex){//使用同步函数
if(flag){
try{
this.wait();
}
catch(InterruptedException e){
}
}
this.name = name;//要同步的代码变成了这两句话了,当然还有下面的依据输出语句
this.sex = sex;
flag = true;
this.notify();
}
public synchronized void out(){
if(!flag){
try{
this.wait();
}
catch(InterruptedException e){
}
}
System.out.println(name+"..."+sex);
flag = false;
this.notify();
}
}
class Input implements Runnable{
Resource r;
Input(Resource r){
this.r = r;
}
public void run(){
int x = 0;
while(true){
if(x == 0){
r.set("zhangsan","man");
}
else{
r.set("丽丽","女");
}
x = (x + 1)%2;
}
}
}
class Output implements Runnable{
Resource r;
Output(Resource r){
this.r = r;
}
public void run(){
while(true){
r.out();
}
}
}
class Test{
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();
}
}
多线程-等待唤醒机制-代码优化
最新推荐文章于 2020-04-11 19:53:39 发布