Skip to content

Instantly share code, notes, and snippets.

@rodionmoiseev
Created February 25, 2012 06:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodionmoiseev/1906895 to your computer and use it in GitHub Desktop.
Save rodionmoiseev/1906895 to your computer and use it in GitHub Desktop.
Solution to Java Puzzle 2
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