gpt4 book ai didi

java - 在所提供示例的上下文中,使用 synchronized(this) 将方法分成多个部分是否有助于提高性能?

转载 作者:行者123 更新时间:2023-11-30 06:52:14 24 4
gpt4 key购买 nike

我是 Java 并发的新手,我在网上看到了一个示例,该示例尝试通过对方法的一部分进行同步来提高性能,同时保持并发。

示例:

public class TwoSums {

private int sum1 = 0;
private int sum2 = 0;

public void add(int val1, int val2){
synchronized(this){
this.sum1 += val1;
this.sum2 += val2;
}
}
}

改进示例:

public class TwoSums {

private int sum1 = 0;
private int sum2 = 0;

public void add(int val1, int val2){
synchronized(this){
this.sum1 += val1;
}
synchronized(this){
this.sum2 += val2;
}
}
}

文章作者提到:

Now two threads can execute the add() method at the same time. One thread inside the first synchronized block, and another thread inside the second synchronized block. This way threads will have to wait less for each other to execute the add() method.

我的问题是,对于改进的示例,即使该方法使用 synchronised(this) 分为两部分,我们仍然在同一个“this”对象上同步,所以即使两个不同的线程可以同时访问方法add,我们仍然不能同时更新sum1sum2的值,正确的?但是作者说我们可以。

我对此很困惑。

最佳答案

嗯。我不认为第二个版本会更快。因为在第二个版本中,第一个线程在第-1行获取了监视器(this),然后即使第二个线程到达,也必须等待第一个线程释放监视器(this)锁定/监控,(并且无法继续)。

此外,2 个同步块(synchronized block)意味着 JVM 发出额外的内存屏障指令,这意味着额外的内存刷新。第二个实际上应该更慢。

关于java - 在所提供示例的上下文中,使用 synchronized(this) 将方法分成多个部分是否有助于提高性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39361587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com