public class Input_OutputDemo2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Res r=new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
class Res
{
private String name;
private String sex;
private boolean flag=false;
synchronized public void set(String name,String sex)
{
if(flag)
try {this.wait();} catch (InterruptedException e) {}
// else{
this.name = name; // this.name = name;
this.sex = sex; // this.sex = sex;
flag=true; // flag=true;
this.notify(); // this.notify();
// }
}
synchronized public void out()
{
if(!flag)
try {this.wait();} catch (InterruptedException e) {}
// else{
System.out.println(name+"-----"+sex); // System.out.println(name+"-----"+sex);
flag=false; // flag=false;
this.notify(); // this.notify();
// }
}
}
class Input implements Runnable
{
private Res r;
public Input(Res r)
{
this.r=r;
}
public void run()
{
int j=0;
for(int i=1;i<50;i++)
{
if(j==0)
{
r.set("mike", "man");
}else
{
r.set("丽丽", "女女");
}
j=(j+1)%2;
}
}
}
class Output implements Runnable
{
private Res r;
public Output(Res r)
{
this.r=r;
}
public void run()
{
for(int i=1;i<50;i++)
{
r.out();
}
}
}
在上面代码中我把蓝色的换成红色的,为啥结果截然不同呢??flag为假时不是就是执行它下面的部分吗??
|