简体   繁体   English

同步语句和单独的非同步方法

[英]Synchronized statements and separate unsynchronized methods

On the Java documentation online I found the following example: 在Java在线文档中,我找到了以下示例:

public void addName(String name) {
    synchronized(this) {
        lastName = name;
        nameCount++;
    }
    nameList.add(name);
}

They state: 他们说:

Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking nameList.add . 如果没有同步的语句,则仅出于调用nameList.add目的,就必须有一个单独的,非同步的方法。

Does someone understand what they mean? 有人明白他们的意思吗?

The source can be found here . 来源可以在这里找到。

The article first introduces synchronized methods - so up to this point, the reader may believe that the unit of granularity of synchronization is a single method. 本文首先介绍了同步方法-到目前为止,读者可能会认为同步粒度单位是单个方法。

And indeed, if synchronized blocks/statements didn't exist, the example above could only be accomplished as: 实际上,如果不存在同步的块/语句,则上面的示例只能通过以下方式实现:

public void addName(String name) {
    doSyncAdd(name);
    nameList.add(name);
}

private synchronized void doSyncAdd(String name) {
    lastName = name;
    nameCount++;
}

So, synchronized statements mean you can keep related code that needs to be synchronized inline. 因此,同步语句意味着您可以保留需要内联的相关代码。 Rather than having to declare a separate method, which both pollutes the namespace and fragments the flow of the code. 不必声明单独的方法,这既会污染名称空间,又会碎片化代码流。 (Well, factoring out methods is good in moderation but it's nicer to have the choice.) (嗯,将方法分解出来是适度的,但是选择起来更好。)

It means that your code snippet can be rewritten as 这意味着您的代码段可以重写为

public void addName(String name) {
    setName(name)
    nameList.add(name);
}

private synchronized void setName(String name) {
    lastName = name;
    nameCount++;
}

ie as synchronized(this) is the same as a synchronized instance (non-static) method the code in the synchronized block can be moved to a synchronized method and called from the unsynchronized method. 即,由于synchronized(this)synchronized实例(非静态)方法相同,因此可以将synchronized块中的代码移至synchronized方法并从非同步方法中调用。 The effect will be the same. 效果将是相同的。

It's trying to depict the need of Synchronized statements compared to Synchronized methods . Synchronized方法相比,它试图描述对Synchronized语句的需求。

If you want to have synchronized updation of lastName and nameCount but not the nameList.add() then Synchronized statements is better option. 如果要同步更新lastNamenameCount而不是nameList.add()则使用同步语句是更好的选择。 Otherwise you would end up creating one synchronized method to update lastName and nameCount and another unsynchronized method to add the name in the list. 否则,您最终将创建一个同步的方法来更新lastName和nameCount,并创建另一个非同步的方法来将名称添加到列表中。

Hope it clarifies. 希望它能澄清。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM