Saturday, February 25, 2012

Java Puzzles

In the Java Specalists newsletter they had a link to some java puzzles from http://wouter.coekaerts.be/puzzles which were rather interesting. The first one had me for a while till I read the hints about hashset and I'm still not quite sure about the second puzzle.

My original solution used Thread.sleep which did not work but after some googling I changed it to wait on the sleeper which did work. I'm not exactly sure why this is but it is to do with Thread.sleep not releasing its lock on the synchronised block whereas the sleeper.wait means that the current thread is now waiting on the original thread.

Hopefully when they publish the solution it will be a bit more clear what is going on here.

package dream;

import sleep.Sleeper;

public class Dream {

    public void dream(Sleeper s) {

        DreamThread dreamThread = new DreamThread();
        dreamThread.sleeper = s;

        new Thread(dreamThread).start();
        try {
//             Thread.sleep(100);
            s.wait(100);
        } catch (InterruptedException e) {
        }
    }

    private class DreamThread extends Dream implements Runnable {

        private Sleeper sleeper;

        @Override
        public void run() {
            sleeper.enter(this);
        }

        public void dream(Sleeper s) {
           
            try {
//                 Thread.sleep(500);
                s.wait(500);
            } catch (InterruptedException e) {
            }
        }
    }
}