使用同步方法而不是同步块有优势吗? [英] Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

查看:190
本文介绍了使用同步方法而不是同步块有优势吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我同步方法对同步块的优点与一个例子?

Can any one tell me the advantage of synchronized method over synchronized block with an example?

推荐答案


<

也许唯一一个(但我不会称之为优势)是你不需要包含对象引用 this

Perhaps the only one ( but I wouldn't call it advantage ) is you don't need to include the object reference this.

方法:

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

封锁:

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

没有优势。

阻止 do 优于方法,最重要的是灵活性,因为您可以使用其他对象作为锁,而同步方法将锁定完整类。

Blocks do have advantages over methods, most of all in flexibility because you can use other object as lock whereas syncing the method would lock the complete class.

比较:

// locks the whole object
... 
private synchronized void someInputRelatedWork() {
    ... 
}
private synchronized void someOutputRelatedWork() {
    ... 
}

Vs。

// Using specific locks
Object inputLock = new Object();
Object outputLock = new Object();

private void someInputRelatedWork() {
    synchronize(inputLock) { 
        ... 
    } 
}
private void someOutputRelatedWork() {
    synchronize(outputLock) { 
        ... 
    }
}

如果方法增长,你仍然可以保持同步部分分离:

Also if the method grows you can still keep the synchronized section separated:

 private void method() {
     ... code here
     ... code here
     ... code here
    synchronized( lock ) { 
        ... very few lines of code here
    }
     ... code here
     ... code here
     ... code here
     ... code here
}

这篇关于使用同步方法而不是同步块有优势吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆