为什么该程序输出的值不是间隔着输出一个人名字、性别和另一个人的名字和性别?总是有重复的。
package zhangli1;
public class ResourceDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
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();
}
}
class Resource{
String name;
String sex;
static boolean flag=false;
public synchronized void set(String name,String sex){
if(flag)
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.name=name;
this.sex=sex;
flag=true;
this.notify();
}
public synchronized void out(String name,String sex){
if(!flag)
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
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("美丽", "女女女女女女女女");
}
else
r.set("JOHN","NAN");
x=(x+1)%2;
}
}
}
class Output implements Runnable{
Resource r;
Output(Resource r){
this.r=r;
}
public void run(){
while(true){
r.out(r.name, r.sex);
}
}
}
输出结果是这样的:
JOHN..........NAN
美丽..........女女女女女女女女
JOHN..........NAN
美丽..........女女女女女女女女
美丽..........女女女女女女女女
美丽..........女女女女女女女女
JOHN..........NAN
美丽..........女女女女女女女女
JOHN..........NAN
美丽..........女女女女女女女女
JOHN..........NAN
美丽..........女女女女女女女女
JOHN..........NAN
美丽..........女女女女女女女女
JOHN..........NAN
美丽..........女女女女女女女女
JOHN..........NAN
美丽..........女女女女女女女女
JOHN..........NAN
美丽..........女女女女女女女女
JOHN..........NAN
美丽..........女女女女女女女女
美丽..........女女女女女女女女
美丽..........女女女女女女女女
JOHN..........NAN
美丽..........女女女女女女女女
|