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

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

问题描述

谁能用一个例子告诉我同步方法相对于同步块的优势?

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

推荐答案

谁能通过一个例子告诉我同步方法相对于同步块的优势?谢谢.

与块相比,使用同步方法没有明显的优势.

There is not a clear advantage of using synchronized method over the block.

也许唯一的(但我不会称其为优势)是您不需要包含对象引用 this.

Perhaps the only one ( but I wouldn't call it an 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...
}

看到了吗?一点优势都没有.

See? No advantage at all.

do虽然比方法有优势,主要是在灵活性方面,因为你可以使用另一个对象作为锁,而同步方法会锁定整个对象.

Blocks do have advantages over methods though, mostly in flexibility because you can use another object as lock whereas syncing the method would lock the entire object.

比较:

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

对比

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

private void someInputRelatedWork() {
    synchronized(inputLock) { 
        ... 
    } 
}
private void someOutputRelatedWork() {
    synchronized(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天全站免登陆