-4

i was working with the synchronized statement and made the following program...synchronized the runn class with this as object reference ..bt smhw the desired output is nt there....

class runn extends Thread {
    String s;

    runn(String a) {
        s=a;
        start();
    }

     public void show() {
        System.out.print("["+s);
        try {
            sleep(50);
        } catch(Exception a){}

        System.out.print("]");
    }

    public void run() {
        synchronized(this) {
            show();
        }
    }
}

public class multi4 {

    public static void main(String[] args) throws InterruptedException{
        new runn("hello ");
        new runn("this is ");
        new runn("multithreading");
    }
}

The output should be :

[hello][this is][multithreading]

but synchronisation is not working smhw

Please help.

4

1 回答 1

2

两个错误:

  • synchronized对个别runn对象。这没有任何效果,因为每个线程使用不同的同步对象。
  • synchronized关键字不会神奇地导致线程按顺序运行。如果您在同一个对象上同步,它只会阻止线程同时尝试执行该synchronized块。它们可能仍以任何顺序运行,但无法交错输出。也就是说,如果你在一个共享对象上,你可以得到例如,但不是。synchronized[this is][hello][multithreading][this is[hello][multithreading]]
于 2013-09-01T14:14:03.433 回答