Java中的同步方法和同步块

时间:2013-07-27 10:05:33

标签: java synchronization

我刚开始使用Java进行同步,我的问题很小。

这是方法:

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

等于:

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

PS

最近我看了两篇关于Java的好东西(从这里得到了我的问题)video 1video 2。你有一些相对的视频(我对用Java和Android编程感兴趣)。

5 个答案:

答案 0 :(得分:0)

是。还有这个:

public static synchronized void method() {
}

相当于:

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

关于视频,只需在youtube上搜索“java同步”。

答案 1 :(得分:0)

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

在语义上等同于

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

答案 2 :(得分:0)

是的。 synchronized方法在方法所属的实例上隐式同步。

答案 3 :(得分:0)

方式

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

阻止

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

块确实比方法更有优势,最重要的是灵活性。唯一真正的区别是同步块可以选择它同步的对象。 synchronized方法只能使用'this'(或同步类方法的相应Class实例)。

synchronized块更灵活,因为它可以竞争任何对象的关联锁,通常是成员变量。它也是更细粒度,因为您可以在块之前和之后执行并发代码,但仍然在方法内。当然,您可以通过将并发代码重构为单独的非同步方法来轻松使用同步方法。使用任何使代码更易于理解的内容。

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

答案 4 :(得分: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
}