Skip to content

Instantly share code, notes, and snippets.

@guohai
Created August 17, 2011 14:31
Show Gist options
  • Save guohai/1151626 to your computer and use it in GitHub Desktop.
Save guohai/1151626 to your computer and use it in GitHub Desktop.
一个非常非常大的int类型数组,用多线程计算和。假设数组长度M线程数量N
import java.util.concurrent.CountDownLatch;
import org.apache.commons.lang.math.RandomUtils;
public class MultipleThreadCalSum {
public static void main(String[] args) {
final int M = 10000000; // 10万个元素
final int N = 100; // 100个线程
int[] ia = new int[M]; // 需要求和的数组
init(ia);
new CalculatorII(ia).start();
// 数组分区partition,多少个线程就分多少partition
// 不考虑空间因素
int m = partition(ia, N);
int l = M - 1;
long[] rst = new long[N];
int start = 0, end = 0;
int s = 0; // 第几个计算工人
CountDownLatch threadSignal = new CountDownLatch(N);// 初始化countDown
while (l >= 0) {
// 求出每段的start,end,每段开启一个线程
// 刚好会开启N个线程
if (l > m) {
end = l;
l = l - m;
start = l + 1;
} else {
end = l;
start = 0;
l = Integer.MIN_VALUE; // 退出
}
new Calculator(ia, start, end, rst, s++, threadSignal).start();
}
// 等待所有线程执行完毕
try {
threadSignal.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 累加结果
long sum = 0;
for (int idx = 0; idx < N; idx++) {
sum += rst[idx];
}
System.out.println("Calculator sum " + sum);
}
private static void init(int[] a) {
int size = a.length;
for (int i = 0; i < size; i++) {
a[i] = RandomUtils.nextInt();
}
}
private static int partition(int[] a, int number) {
int l = a.length;
int t = l / number; // 获得理想的每个分区元素个数
if (number * t < l) {
// 如果元素个数超过,则每个区增加一个元素
t++;
}
return t;
}
}
class Calculator extends Thread {
int[] part;
long[] t;
int start, end, s;
CountDownLatch latch;
public Calculator(int[] a, int start, int end, long[] rst, int s,
CountDownLatch singal) {
this.part = a;
this.t = rst;
this.start = start;
this.end = end;
this.s = s;
this.latch = singal;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
t[s] += part[i];
}
this.latch.countDown();
}
}
class CalculatorII extends Thread {
int[] ia;
public CalculatorII(int[] a) {
this.ia = a;
}
@Override
public void run() {
long sum = 0;
for (int i = 0; i < ia.length; i++) {
sum += ia[i];
}
System.out.println("CalculatorII sum " + sum);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment