Created
February 25, 2012 06:24
-
-
Save rodionmoiseev/1906895 to your computer and use it in GitHub Desktop.
Solution to Java Puzzle 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class JavaPuzzle2 { | |
public static void main(String[] args) { | |
//test | |
if (new Sleeper().sleep(new Dream()) != 0) { | |
System.out.println("Still dreaming"); | |
} | |
} | |
} | |
class Sleeper { | |
private int level; | |
public synchronized int sleep(Dream dream) { | |
level++; | |
try { | |
dream.dream(this); | |
} finally { | |
level--; | |
} | |
return level; | |
} | |
} | |
class Dream { | |
public void dream(final Sleeper sleeper) { | |
Thread th = new Thread(new Runnable() { | |
@Override | |
public void run() { | |
sleeper.sleep(new Dream() { | |
@Override | |
public void dream(Sleeper sleeper) { | |
try { | |
sleeper.wait(); | |
} catch (InterruptedException e) { | |
} | |
} | |
}); | |
} | |
}); | |
th.setDaemon(true); | |
th.start(); | |
try { | |
sleeper.wait(1000); | |
} catch (InterruptedException e) { | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment