Different output for synchronization on threads

48 Views Asked by At

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();
    }
}
0

There are 0 best solutions below