1

我有一个关于 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 */);
}

有人可以帮我澄清一下吗?

4

1 回答 1

3

由于您的计算对多个AtomicXXX对象 ( i, j) 进行操作,因此它们不是线程安全的。AtomicXXX语义是通过比较和交换 (CAS)指令实现的,这些指令一次不支持多个占位符。您需要一个外部监视器锁以使其成为线程安全的。

于 2018-12-05T17:46:32.767 回答