解决方案 »

  1.   

    因为你Read执行的太快了,使writeFlag长期处于false状态。write和read的地方各加一个随机的sleep的,使代码写的更慢一点,你再试试看,理解理解。
      

  2.   

    其实你想交替输出男女信息的话,在set()方法和read()方法中没必要加那么多if else。。
    如下即可:
    public synchronized void set(String name, String sex) {
    //现在的set()方法既相当于你将else注释掉后的情况,if(..){} else if(..){}语句只会执行if或者else里面的语句,而你将else去掉后就变成了两个if语句
    //你原来的代码变成两个if语句后,这两个if里面的代码都会执行
    if (writenFlag == false) {
    this.name = name;
    this.sex = sex;
    this.writenFlag = true;
    this.notifyAll();
    try {
    this.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    } public synchronized void read() {
    if (writenFlag == true) {
    System.out.println(this.name + " - " + this.sex);
    this.writenFlag = false;
    this.notifyAll();
    try {
    this.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }set()方法中只需要关注标志位为false的情况,既当前未写入数据时写入数据,然后唤醒读取线程读取数据并让写入线程等待。
    同理:read()方法中只需关注标注为true的情况,既当前已写入数据后读取数据,然后唤醒写入线程并让读取线程等待。
    考虑到你这里的情况,完全可以不用wait()和notifyAll()方法,通过writeFlag标志来控制即可,如下
    public synchronized void set(String name, String sex) {
    if (writenFlag == false) {
    this.name = name;
    this.sex = sex;
    this.writenFlag = true;
    }
    } public synchronized void read() {
    if (writenFlag == true) {
    System.out.println(this.name + " - " + this.sex);
    this.writenFlag = false;
    }
    }
      

  3.   

    我自己今天已经大概找到原因了,是因为我没有掌握好if...else的用法,
    在这个程序里显现出来了,debug和打印花了不少时间,
    如果早点看到你的回复就好了。
    你的回复又开阔了我的思路,非常感谢你!