public class Res {
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;
this.flag=true;
this.notify();
}
public synchronized void out(){
if(!flag)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+"...."+sex);
this.flag=false;
this.notify();
}
}
public class Input implements Runnable {
private Res r;
Input(Res r) {
this.r = r;
}
public void run() {
int x = 0;
while (true) {
if (x == 0) {
r.set("tom", "man");
} else {
r.set("李丽", "女");
}
x = (x + 1) % 2;
}
}
}
public class Output implements Runnable {
private Res r;
Output(Res r) {
this.r = r;
}
public void run() {
while (true) {
r.out();
}
}
}
public class TestDemo {
public static void main(String[] args) {
Res r=new Res();//Res(String name, String sex)
Input in=new Input(r);//
Output out=new Output(r);//
Thread td1=new Thread(in);
Thread td2=new Thread(out);
td1.start();
td2.start();
}
}
Input in=new Input(r); 括号里面为什么放个r