class Demo {
public static void main(String[] args) {
Res s = new Res();
Input in = new Input(s);
Output out = new Output(s);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
class Input implements Runnable {
private Res s;
Input(Res s) {
this.s = s;
}
public void run() {
boolean flag = true;
while (true) {
synchronized (s) {
if (s.x == 1)
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (flag) {
s.setName("zhangsan");
s.setSex("nan");
flag = false;
} else {
s.setName("李四");
s.setSex("女");
flag = true;
}
s.x = 1;
s.notify();
}
}
}
}
class Output implements Runnable {
private Res s;
Output(Res s) {
this.s = s;
}
public void run() {
while (true) {
synchronized (s) {
if (!(s.x == 1))
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(s.getName() + s.getSex());
s.x = 0;
s.notify();
}
}
}
}
class Res {
int x = 0;
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}