53 lines
1.2 KiB
Java
53 lines
1.2 KiB
Java
package atomic2;
|
|
|
|
import java.util.concurrent.atomic.AtomicLong;
|
|
import test.Test;
|
|
|
|
// @NotThreadSafe
|
|
public class SingleUpdatePerThreadAtomic {
|
|
private static AtomicLong result;
|
|
|
|
private SingleUpdatePerThreadAtomic() {
|
|
// Cannot be instantiated
|
|
}
|
|
|
|
private static void addPartialResult(long partial) {
|
|
result.getAndAdd(partial);
|
|
}
|
|
|
|
public static long sum(int[] nums) throws Exception {
|
|
result = new AtomicLong(0);
|
|
Thread[] threads = new Thread[Test.NUM_THREADS];
|
|
int size = (int) Math.ceil((double) nums.length / Test.NUM_THREADS);
|
|
for (int i = 0; i < Test.NUM_THREADS; i++) {
|
|
threads[i] = new Thread(
|
|
new SumSingleUpdate(nums, i * size, (i + 1) * size));
|
|
threads[i].start();
|
|
}
|
|
for (Thread thread : threads) {
|
|
thread.join();
|
|
}
|
|
return result.longValue();
|
|
}
|
|
|
|
static class SumSingleUpdate implements Runnable {
|
|
private final int[] nums;
|
|
private final int low;
|
|
private final int high;
|
|
|
|
public SumSingleUpdate(int[] nums, int low, int high) {
|
|
this.nums = nums;
|
|
this.low = low;
|
|
this.high = Math.min(high, nums.length);
|
|
}
|
|
|
|
public void run() {
|
|
long partialSum = 0;
|
|
for (int i = low; i < high; i++) {
|
|
partialSum += nums[i];
|
|
}
|
|
SingleUpdatePerThreadAtomic.addPartialResult(partialSum);
|
|
}
|
|
}
|
|
}
|