package comm;
class Res {
String name;
String sex;
boolean flag = false;
public synchronized void set(String name, String sex) {
if (flag)
try {
this.wait();
} catch (InterruptedException e) {
}
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}
public synchronized void out() {
if (!flag)
try {
this.wait();
} catch (InterruptedException e) {
}
System.out.println(name + " , " + sex);
flag = false;
this.notify();
}
}
class Input implements Runnable {
private Res r;
public 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;
public Output(Res r) {
this.r = r;
}
public void run() {
while (true)
r.out();
}
}
public class InputOutoutDemo2 {
public static void main(String[] args) {
Res r = new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
代码优化
最新推荐文章于 2023-08-24 15:46:50 发布