这个问题一再被问到,但我仍有疑问.当人们说同步创建了一个内存屏障时,这个内存屏障适用于什么,任何缓存变量?这看起来不太可行.
所以,由于这个疑问,我写了一些看起来像这样的代码:
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)