本帖最后由 孙百鑫 于 2013-6-19 09:08 编辑
[code]class Res1 {
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;
flag = true;
this.notify();
}
}
public synchronized void out() {
if (!flag)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+"........"+sex);
flag = false;
this.notify();
}
}
class Input1 implements Runnable {
private Res1 r;
Input1(Res1 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 Output1 implements Runnable {
private Res1 r;
Output1(Res1 r) {
this.r = r;
}
public void run() {
while (true) {
r.out();
}
}
}
public class InputOutputDemo1 {
public static void main(String[] args) {
Res1 r = new Res1();
new Thread(new Input1(r)).start();
new Thread(new Output1(r)).start();
/*Input1 in = new Input1(r);
Output1 out = new Output1(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();*/
}
}
我按照毕老师的视频代码敲出来的,怎么运行不出结果?请大家帮忙看看····
|