本帖最后由 xuemeng 于 2013-5-14 21:09 编辑
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;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
通讯方法必须用监视器对象来调用才对, 你的监视器对象是 s, 我就用s 对象来调用 wait() 和notify()方法, 这样代码就没问题了 |