繁体   English   中英

原子中的Java计算

[英]Java calculation in Atomic

我对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 */);
}

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

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

暂无
暂无

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

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