【发布时间】:2016-11-02 01:47:17
【问题描述】:
在下面的代码中:
我在 2 个线程中更新 num[1]=0 的 AtomicIntegerArray num 1000 次。
在主线程的 2 个线程的末尾;num[1] 的值不应该是 2000,因为在 AtomicIntegerArray 中不应该有数据竞争。
但是我得到的随机值
代码:
import java.util.concurrent.atomic.AtomicIntegerArray;
public class AtomicIntegerArr {
private static AtomicIntegerArray num= new AtomicIntegerArray(2);
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new MyRun1());
Thread t2 = new Thread(new MyRun2());
num.set(0, 10);
num.set(1, 0);
System.out.println("In Main num before:"+num.get(1));
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("In Main num after:"+num.get(1));
}
static class MyRun1 implements Runnable {
public void run() {
for (int i = 0; i < 1000; i++) {
num.set(1,num.get(1)+1);
}
}
}
static class MyRun2 implements Runnable {
public void run() {
for (int i = 0; i < 1000; i++) {
num.set(1,num.get(1)+1);
}
}
}
}
编辑:添加 num.compareAndSet(1, num.get(1), num.get(1)+1); 而不是 num.set(1,num.get(1)+1); 也不起作用。
【问题讨论】:
标签: java multithreading concurrency atomicreference