This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
PF3/hw1/Ex1/src/simple1/MultipleUpdatesPerThread.java

51 lines
1.1 KiB
Java

package simple1;
import test.Test;
// @NotThreadSafe
public class MultipleUpdatesPerThread {
private static long result;
private MultipleUpdatesPerThread() {
// Cannot be instantiated
}
private static void addPartialResult(long partial) {
result += partial;
}
public static long sum(int[] nums) throws Exception {
result = 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 SumMultipleUpdates(nums, i * size, (i + 1) * size));
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
return result;
}
static class SumMultipleUpdates implements Runnable {
private final int[] nums;
private final int low;
private final int high;
public SumMultipleUpdates(int[] nums, int low, int high) {
this.nums = nums;
this.low = low;
this.high = Math.min(high, nums.length);
}
public void run() {
for (int i = low; i < high; i++) {
MultipleUpdatesPerThread.addPartialResult(nums[i]);
}
}
}
}