本帖最后由 袁錦泰 于 2012-5-29 10:42 编辑
- class Res {
- private String name;
- private String gender;
- private boolean flag;
- public synchronized void set(String name, String gender) {
- if (this.flag) {
- try {
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- } else {
- this.name = name;
- this.gender = gender;
- }
- this.flag = true;
- this.notify();
- }
- public synchronized void out() {
- if (!this.flag) {
- try {
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- } else {
- System.out.println(this.name + "," + this.gender);
- }
- this.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("zhangsan", "male");
- } else {
- r.set("lisi", "female");
- }
- 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();
- }
- }
复制代码 部分结果为:- zhangsan,male
- zhangsan,male
- zhangsan,male
- zhangsan,male
- zhangsan,male
- lisi,female
- lisi,female
- lisi,female
- lisi,female
- lisi,female
- zhangsan,male
- zhangsan,male
复制代码 复习之前所学,我看了许久找不到问题所在,为何出书结果是批量输出,而不是有顺序的分别逐个输出.
请各位细心人帮忙分析一下哪里有错误. |
|