class Resource{
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){
e.printStackTrace();
}
this.name = name;
this.sex = sex;
flag = true ;
this.notify();
}
public synchronized void out(){
if(!flag )
try{
this.wait();
} catch(InterruptedException e){
e.printStackTrace();
}
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( "mike","男" );
} else{
r.set( "lili","女" );
}
x = (x + 1)%2;
}
}
}
//输出
class Output implements Runnable{
Resource r;
Output(Resource r){
this.r = r;
}
public void run(){
while(true ){
r.out();
}
}
}
class ResourceDemo {
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();//开启线程
}
}
如果flag设为false的话,那为什么if(flag)大括号中的内容还可以运行?
甫艾蒽廷
相关分类