gpt4 book ai didi

Java 在原子操作上同步

转载 作者:行者123 更新时间:2023-11-29 09:48:40 25 4
gpt4 key购买 nike

这个 Java 类是线程安全的还是 reset 方法也需要同步?如果是,有人可以告诉我原因吗?

public class NamedCounter {
private int count;
public synchronized void increment() { count++; }
public synchronized int getCount() { return count; }
public void reset() { count = 0; }
}

最佳答案

不是没有同步 rest() 和添加更多方法。您会遇到需要更多方法的情况。例如

NamedCounter counter = new NamedCounter();
counter.increment();
// at this exact time (before reaching the below line) another thread might change changed the value of counter!!!!
if(counter.getCount() == 1) {
//do something....this is not thread safe since you depeneded on a value that might have been changed by another thread
}

要解决上述问题,您需要类似的东西

NamedCounter counter = new NamedCounter();
if(counter.incrementAndGet()== 1) { //incrementAndGet() must be a synchronized method
//do something....now it is thread safe
}

相反,使用涵盖所有情况的 Java 内置类 AtomicInteger。或者,如果您正在尝试学习线程安全,请使用 AtomicInteger 作为标准(以供学习)。

对于生产代码,请毫不犹豫地使用 AtomicInteger!请注意,使用 AtomicInteger 不会自动保证代码中的线程安全。您必须使用 api 提供的方法。他们在那里是有原因的。

关于Java 在原子操作上同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17465502/

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