为什么执行不出结果,哪出现了问题呢?
public class ThreadMain {
public static void main(String args[]) {
Q q = new Q();
new Thread(new Producer(q)).start();
new Thread(new Cousumer(q)).start();
}
}
class Producer implements Runnable {
Q q;
public Producer(Q q) {
super();
this.q = q;
}
@Override
public void run() {
int i = 0;
while (true) {
if (i == 0) {
q.put("zheng", "male");
} else {
q.put("zhao", "female");
}
i = (i + 1) % 2;
}
}
}
class Q {
private String name = "unkown";
private String sex = "unkown";
private boolean bFull = false;
public synchronized void put(String name, String sex) {
if (bFull) {
try {
wait();
} catch (Exception e) {
// TODO: handle exception
}
this.name = name;
try {
Thread.sleep(1);
} catch (Exception e) {
// TODO: handle exception
}
this.sex = sex;
bFull = true;
notify();
}
}
public synchronized void get() {
if (!bFull) {
try {
wait();
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(name);
System.out.println(":" + sex);
bFull = false;
notify();
}
}
}
class Cousumer implements Runnable {
Q q;
public Cousumer(Q q) {
super();
this.q = q;
}
@Override
public void run() {
while (true) {
q.get();
}
}
} |
|