0

What is the difference between having while(true) and then then synchronzed(object) within while loop... and the other way round with synchronzized(object) and while (true) whithin it? What difference will it make logically? I find no difference wrt output.

public class H extends Thread   {
    String info = "";
    public H (String info) {
        this.info    = info;
    }
    public synchronized void run () {
       try {

        while ( true )  {
            System.out.println(info);
            this.notify();
            this.wait();
        }
       } catch ( Exception e )  {}
    }
    public static void main (String args []) {
        new H("0").start();
        new H("1").start();
    }
}


public class X extends Thread   {
    private String info;
    static Object o = new Object();
    public X (String info) {
        this.info    = info;
    }
    public void run () {
        while ( true )  {
            synchronized ( o ) {
                System.out.println(info);
                try {
                    o.notify();
                    sleep(100);
                    o.wait(1);
                } catch ( Exception e ) { }
            }
        }
    }
    public static void main (String args []) {
        ( new X("0") ).start();
        ( new X("1") ).start();
    }
}
  • I think you should use some code sample, in order to make your question answerable. – Giulio Franco Dec 06 '13 at 01:21
  • Just with what you said, the only difference is that, when the while is outside, the lock is released and re-acquired multiple times, giving other objects an opportunity to acquire it, whereas it is never released in your second option (unless you have some `.wait()` calls in the code) – Giulio Franco Dec 06 '13 at 01:22

0 Answers0