Java 谜题 2:梦境

你有没有从梦中醒来,然后发现你真的还在做梦?如果你醒来,你怎么知道你回到了现实?这个难题实现了该问题的解决方案:当您进入和退出梦想时,您可以计算梦境的递归级别:

package sleep;
 
import dream.Dream;
 
public class Sleeper {
    private int level;
     
    public synchronized int enter(Dream dream) {
        level++;
        try {
            dream.dream(this);
        } finally {
            level--;
        }
        return level;
    }
}

睡眠者开始睡觉并进入梦境(第一级)。他可以在梦里做一个梦,甚至进入更深层次的梦。但当他离开表层的梦时,他再次醒来,所以他应该再次回到零级,对吧?

package sleep;
 
import dream.Dream;
 
public class Main {
    public static void main(String[] args) {
        if (new Sleeper().enter(new Dream()) != 0) {
            // The goal is to reach this line
            System.out.println(
"Am I still dreaming?");
        }
    }
}

 levels 计数看起来非常安全,所以这似乎是不可能的:

  • 每次进入梦境level都会增加。由于finally阻挡,没有办法离开梦境而不再减少它。
  • synchronized块确保没有其他线程可以同时调用它。从梦的方法返回级别,以确保它在synchronized块内读取。
  • 进入梦境时lever必须是零,那么从它返回的值也必须为零,因为即使我们递归地调用它,我们也必须输入与退出同样多的梦境。

// this is the only file you're allowed to edit
package dream;
 
import sleep.Sleeper;
 
public class Dream {
    public void dream(Sleeper s) {
       
// TODO implement me
    }
}

你能找到这个推理中的缺陷吗?你能想象一个真正奇怪的梦想会让睡眠者失去理智吗?