相关疑难解决方法(0)

Java数组:synchronized + Atomic*,还是同步的?

这个问题一再被问到,但我仍有疑问.当人们说同步创建了一个内存屏障时,这个内存屏障适用于什么,任何缓存变量?这看起来不太可行.

所以,由于这个疑问,我写了一些看起来像这样的代码:

final AtomicReferenceArray<Double> total=new AtomicReferenceArray<Double>(func.outDim);
for(int i=0; i<func.outDim; i++) total.set(i, 0.);
for(int i=0; i<threads; i++){
    workers[i]=new Thread(new Runnable(){
        public void run() {
            double[] myPartialSum=new double(func.outDim);
            //some lengthy math which fills myPartialSum...

            //The Atomic* guarantees that I'm not writing local copies of the Double references (whose value are immutables, so it's like an array of truly volatile doubles) in variable total, synchronized(total) atomizes the sum
            synchronized(total){ for(int i=0; i<func.outDim; i++) total.set(i, total.get(i)+myPartialSum[i]); }
        };
    workers[i].start();
}
//wait for workers to …
Run Code Online (Sandbox Code Playgroud)

java arrays atomic volatile synchronized

4
推荐指数
1
解决办法
331
查看次数

标签 统计

arrays ×1

atomic ×1

java ×1

synchronized ×1

volatile ×1