本帖最后由 钱志新 于 2013-2-2 00:30 编辑
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 (Exception e) {
}
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}
public synchronized void out() {
if (!flag)
try {
this.wait();
} catch (Exception e) {
}
System.out.println(name + "..." + sex);
flag = false;
this.notify();
}
}
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("mike", "man");
else
r.set("莉莉", "女");
x = (x + 1) % 2;
}
}
}
class Output implements Runnable {
private Res r;
Output(Res r) {
this.r = r;
}
public void run() {
while (true) {
r.out();
}
}
}
public class InputOutputDemo {
public static void main(String args[]) {
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
//程序是毕老师第12天代码优化视频中的,在我电脑上就出现如图错误,求指教。
|
-
2.jpg
(17.85 KB, 下载次数: 38)
不解。
|