我有一个关于 Java 的小问题AtomicInteger
。我知道我可以实现线程安全的计数器。但我找不到任何关于复杂计算的信息AtomicInteger
。
例如,我有这个计算(i 和 j 是对象变量,“this”):
public void test(int x) {
i = i + ( j * 3 ) + x
}
是否可以仅使用 使此方法成为线程安全的AtomicInteger
?
这是有效的吗?
public void test(int x) {
do {
int tempi = i.get();
int tempj = j.get();
int calc = tempi + ( tempj * 3 ) + x;
} while (i.compareAndSet(tempi, calc));
}
我认为不是因为线程可以在计算时更改 j。为避免这种情况,我必须控制计算时是否更改 j。但我没有在AtomicInteger
.
伪代码:
public void test(int x) {
do {
int tempi = i.get();
int tempj = j.get();
int calc = tempi + ( tempj * 3 ) + x;
} while (i.compareAndSet(tempi, calc) && j.compare(tempj) /* changed */);
}
有人可以帮我澄清一下吗?