2013-07-27 136 views
0

我剛剛開始在Java中進行同步,並且我有一個小問題。Java中同步方法ans同步塊

這是方法:

public synchronized void method() { 
    // ... do staff ... 
} 

等於:

public void method() { 
    synchronize(this) { 
     // ... do staff ... 
    } 
} 

PS

最近我看了關於Java 2個好confs(並從此我的問題是)video 1video 2。你有一些相關的視頻(我對Java和Android編程感興趣)。

+0

的http://計算器。com/questions/574240/synchronized-block-vs-synchronized-method –

+1

您需要參加一些會議,但這不是會議漏洞。 –

+0

(1)是的。 (2)你不需要任何視頻來建立這個,只需要現有的文檔。 (3)如果你認爲你將要學習計算機視頻編程,你會有另一種想法。 – EJP

回答

0

是的。另外這款:

public static synchronized void method() { 
} 

等同於:

public static void method() { 
    synchronized (EnclosingClass.class) { 
    } 
} 

關於影片,只需在YouTube的搜索 「Java同步」。

0
public void method() { 
    synchronize(this) { 
     // ... do staff ... 
    } 
} 

是語義上等同於

public synchronized void method() { 
    // ... do staff ... 
} 
0

是的。同步方法在該方法所屬的實例上隱式同步。

0

方法

public synchronized void method() { // blocks "this" from here.... 
    ... 
    ... 
    ... 
} // to here 

public void method() { 
    synchronized(this) { // blocks "this" from here .... 
     .... 
     .... 
     .... 
    } /// to here... 
} 

塊也有一些對方法的優點,最重要的靈活性的。唯一真正的區別是同步塊可以選擇它同步的對象。同步方法只能使用'this'(或者對應的類實例用於同步類方法)。

同步塊更靈活,因爲它可以競爭任何對象的關聯鎖,通常是成員變量。這也是更精細的,因爲你可以在塊之前和之後執行併發代碼,但仍然在方法中。當然,通過將併發代碼重構爲單獨的非同步方法,您可以輕鬆使用同步方法。使用任何一種方式使代碼更易於理解。

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

+1

複製內容時請提及來源! – NINCOMPOOP

0

代碼outside synchronized block可以同時通過multiple threds訪問。

public void method(int b) { 
    a = b // not synchronized stuff 
    synchronize(this) { 
     // synchronized stuff 
    } 
} 

這將始終保持同步:

public synchronized void method() { 
    // synchronized stuff 
}