2013-02-15 38 views
2

這兩個代碼塊的行爲是否相同?您可能會認爲這些運行方法是從線程調用的。將方法同步或將同步塊添加到方法之間有區別嗎?

public synchronized void run() { 
    System.out.println("A thread is running."); 
} 

或者

static Object syncObject = new Object(); 

public void run() { 
    synchronized(syncObject) { 
     System.out.println("A thread is running."); 
    } 
} 
+1

@ Eng.Fouad指出它們鎖定不同的對象。對? – Gray 2013-02-15 17:36:12

+0

謝謝,在發帖前我沒有看到那篇文章(對不起)。 – user1420042 2013-02-15 17:38:31

回答

6
public synchronized void run() 
{ 
    System.out.println("A thread is running."); 
} 

等同放着清單:

public void run() 
{ 
    synchronized(this) // lock on the the current instance 
    { 
     System.out.println("A thread is running."); 
    } 
} 

,併爲您的信息:

public static synchronized void run() 
{ 
    System.out.println("A thread is running."); 
} 

等同放着清單:

public void run() 
{ 
    synchronized(ClassName.class) // lock on the the current class (ClassName.class) 
    { 
     System.out.println("A thread is running."); 
    } 
} 
+1

只需要一個小記錄就可以了。我相信,採用同步方法會有一定的益處/防禦性。它減少了一些偶然的機會,一些沒有經驗的人會在同步塊之外添加一些代碼的方法。 – 2013-02-15 17:40:02

+0

@VictorRonin +1我同意。 – 2013-02-15 17:42:44

0

不,你把它是沒有區別的,但將是一個靜態的方法,同步塊將有封閉類的類對象的鎖。