2013-09-22 58 views
4

我在理解同步關鍵字功能時遇到了一些麻煩。 根據java文檔和其他教程,有人說,當使用synchronized關鍵字時,兩個線程之間不可能在該方法的語句之間交織。執行同步語句執行交錯執行

但是,請參閱下面的一段代碼。

public class LockThread implements Runnable { 
    String name; 
    public LockThread(String name) { 
      this.name = name; 
    } 
    public static void main(String[] args) { 
      new Thread(new LockThread("a")).start(); 
      new Thread(new LockThread("b")).start(); 
    } 
    public void run() { 
      locked(Thread.currentThread().getId()); 


    } 

synchronized void locked(long l) { 
     System.out.println(name+"-"+l + "---> Printed from " + Thread.currentThread().getName()); 
     System.out.println(name+"-"+l + "---> Printed from " + Thread.currentThread().getName()); 
} 

}  

按我的理解,節目輸出應始終以一種線程0和線程1不應交錯.. 但執行這段代碼多次,我得到一個交錯輸出..

 
    With interleaving (Output I expect) 
    a-9 ---> Printed from Thread-0 
    a-9 ---> Printed from Thread-0 
    b-10 ---> Printed from Thread-1 
    b-10 ---> Printed from Thread-1 

Without Interleaving (This is one another output I see for the same code above) 
    a-9 ---> Printed from Thread-0 
    b-10 ---> Printed from Thread-1 
    a-9 ---> Printed from Thread-0 
    b-10 ---> Printed from Thread-1 

請幫助我理解這個問題..提前

謝謝..

+0

您需要使用通用鎖 - 例如,您可以使該方法爲靜態,並且您將獲得預期的輸出。 – assylias

回答

5

的​​KEYW ord阻止兩個線程運行在同一個對象上同步的代碼。

您的每個線程正在同步一個不同的對象(this),所以它不起作用。

+1

知道了!謝謝.. – rakpan