The two programs produces different outputs. Why? And why there is repeated 0101 for the first program and not for the second program? Also, the output of the forst program if seen with system currrent time, I see that there are many times when 1 and 0 printed have the same time. How?

What is the thing that resuts in the difference between the two codes?

This is the program with synchronized object example.

public class T extends Thread   {
    private String info;
    static Object o = new Object();
    public T (String info) {
        this.info    = info;
    }
    public void run () {
        synchronized ( o ) {
            while ( true )  {
                System.out.println(info);
                try {
                    o.notify();
                    sleep(100);
                    o.wait();
                } catch ( Exception e ) { }
            }
        }
    }
    public static void main (String args []) {
        ( new T("0") ).start();
        ( new T("1") ).start();
    }
}




Program 2:

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();
    }
}
有帮助吗?

解决方案

In program 1, two threads are syncronized with static Object o = new Object();, which is class variable. Only one of two thread can enter the synchronized block.

But each of the threads in program 2 is synchronized with itself. One does not wait for the other releasing the lock. They are executed independantly.

If the variable o is declared as instance member of class T ( without static), the result is same as program 2.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top