问题在27~41行的注释里import static java.lang.Thread.sleep;class Main
{
    public static void main(String[] args) {
        Resource r=new Resource();
        input input=new input(r);
        output output=new output(r);
        new Thread(input).start();
        new Thread(output).start();
    }
}class Resource
{
    private String name;
    private String sex;
    private boolean flag=true;
    public synchronized void set(String name,String sex) {
        if (!flag)
            try {this.wait();} catch (InterruptedException e) { }
        this.name = name;
        this.sex = sex;
        flag = false;
        this.notify();        /*
        下面这段代码替换上面那段,为什么等待/唤醒机制失效了?
         if (!flag)
         {
            try {this.wait();} catch (InterruptedException e) {}
         }
        else
        {
            this.name = name;
            this.sex = sex;
            flag = false;
            this.notify();
        }        */    }
    public synchronized void print() {
        if (flag)
            try {this.wait();} catch (InterruptedException e) { }
        System.out.println(name + "\t\t" + sex);
        flag = true;
        this.notify();
    }
}class input implements Runnable
{
    Resource r;
    input(Resource r)
    {
        this.r=r;
    }
    public void run()
    {
        int x = 0;
        while(true)
        {
            if(x==0)
            {
                r.set("mike","male");
            }
            else
            {
                r.set("mary","female");
            }
            x = (x+1)%2;
        }
    }
}class output implements Runnable {
    Resource r;
    output(Resource r) {
        this.r = r;
    }
    public void run() {
        while (true) {
            r.print();
        }
    }
}

解决方案 »

  1.   

    把else {} 去掉就可以了
      

  2.   

    为什么呢?触发wait( ) 后,下面的语句还会执行么?
      

  3.   

    我觉得不是else的问题,而是你flag的值设置反了。
    你的原意是如果名字和性别设定好了,flag 设置成true, 在print里面打印,打印完在设置成false,表明已经打印完成。
    如果flag还是true的时候,就表示还没有打印,set方法就要等。调换一下flag的赋值顺序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();
     
            /*
            下面这段代码替换上面那段,为什么等待/唤醒机制失效了?
             if (!flag)
             {
                try {this.wait();} catch (InterruptedException e) {}
             }
            else
            {
                this.name = name;
                this.sex = sex;
                flag = true;
                this.notify();
            }
     
            */
     
        }
        public synchronized void print() {
            if (flag)
                try {this.wait();} catch (InterruptedException e) { }
            System.out.println(name + "\t\t" + sex);
            flag = false;
            this.notify();
        }