gpt4 book ai didi

java - 在多线程应用程序中使用带有 volatile 原语的条件运算符是否安全

转载 作者:行者123 更新时间:2023-11-29 07:13:51 25 4
gpt4 key购买 nike

下面的代码 list 中,Statement 1 和Statement 2 线程安全吗?他们正在使用 VolatileIntWrapper

如果它们不是线程安全的,哪些语句需要包装在同步块(synchronized block)中?

public class Demo {

public static void main(String[] args) {

VolatileIntWrapper volatileIntWrapper = new VolatileIntWrapper() ;

for(int i = 1 ; i <= 5 ; ++i){
new ModifyWrapperIntValue(volatileIntWrapper).start() ;
}
}
}

class VolatileIntWrapper{
public volatile int value = 0 ;
}

class ModifyWrapperIntValue extends Thread{

private VolatileIntWrapper wrapper ;
private int counter = 0 ;

public ModifyWrapperIntValue(VolatileIntWrapper viw) {
this.wrapper = viw ;
}

@Override
public void run() {

//randomly increments or decrements VolatileIntWrapper primitive int value

//we can use below statement also, if value in VolatileIntWrapper is private
// wrapper.getValue() instead of wrapper.value
//but, as per my understanding, it will add more complexity to logic(might be requires additional synchronized statements),
//so, for simplicity, we declared it public


//Statement 1
while(wrapper.value > -1500 && wrapper.value < 1500){
++counter ;
int randomValue = (int) (Math.random() * 2) ;

//Statement 2
wrapper.value += (randomValue == 0) ? 1 : -1 ;
}

System.out.println("Executed " + counter + " times...");
}
}

最佳答案

volatile keyword为读取和写入字段提供内存屏障。这意味着多个线程可以访问该字段并保证读取最新值,并且保证它们的写入被其他线程看到。

什么 volatile 做的是围绕操作顺序提供任何保证——尤其是当您有多个读写语句时。在您的代码中,您正在访问 volatile int循环中的几个地方:

    while(wrapper.value > -1500 && wrapper.value < 1500){
...
wrapper.value += (randomValue == 0) ? 1 : -1 ;
}

此处无法保证操作顺序。在线程 A 测试 value > -1500 之后立即,另一个线程可能会在 线程 A 可以测试之前更改它 value < 1500 .或者线程 A 可能会执行两个测试,然后线程 B 可能会执行两个测试,然后线程 A 会分配值,然后线程 B 会分配值。这就是multithreading race conditions的性质.

while循环是我怀疑会被认为有错误的代码部分,除非您围绕它进行同步。您应该执行以下操作。同步该部分后,synchronized关键字本身提供内存屏障,因此 volatile关键字是不必要的。

   synchronized (wrapper) {
while (...) {
...
}
}

关于java - 在多线程应用程序中使用带有 volatile 原语的条件运算符是否安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11464869/

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