class Res {
private String name;
private String sex;
private boolean flag = false;
public synchronized void setNameSex(String name, String sex) {
if (flag) {
this.wait();
}
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}
public synchronized output() {
if (!flag) {
wait();
}
System.out.println("output--" + res.getName() + "---" + res.getSex());
falg = true;
this.notify();
}
}
class Input implements Runnable {
private Res res;
private Object obj = new Object();
public Input(Res res) {
this.res = res;
}
@Override
public void run() {
int i = 0;
while (true) {
synchronized(res) {
if (i % 2 == 0) {
res.setNameSex("name", "sex");
} else {
res.setNameSex("姓名", "性别");
}
i++;
System.out.println("input--" + res.getName() + "---" + res.getSex());
}
}
}
}
class Output implements Runnable {
private Res res;
public Output(Res res) {
this.res = res;
}
@Override
public void run() {
while (true) {
synchronized(res) {
res.output();
}
}
}
}
/*
为什么这些操作线程的方法要定义在Object类中呢?
因为这这些方法的操作同步线程时,都必须要标识它们所操作线程只有的锁.
只在同一个锁上的被等待线程,可发被同一个锁上的notify唤醒.
不可以对不同锁中的线程进行唤醒.
而锁可以是任意对象,所以这些方法在Object中定义.
*/
public class InputOutputDemo {
public static void main(String[] args) {
Res res = new Res();
new Thread(new Input(res)).start();
new Thread(new Output(res)).start();
}
}