java采用多線程的方法計算一個數組的各個元素之和。具體來說,該數組為 整型數組 a,有 300 個元素。在 main 函數中,對該數組的每個元素進行指派,值為一 個 1-100 的随機數。然後建立 3 個線程,第 1 個線程負責計算 a[0]~a[99]這 100 個元素 之和;第 2 個線程負責計算 a[100]~a[199]這 100 個元素之和;第 3 個線程負責計算 a[200]~a[299]這 100 個元素之和。最後在 main 函數中彙集各個線程的計算結果,然後 算出最終的結果,即 a[0]~a[299]這 300 個元素的總和,并且列印出來。
package Unit6;
import java.util.Random;
/**
* Created by wfb 2019.11.27
*/
public class ParallelSum {
public static void main(String[] args) {
int i;
int finalsum, mysum = 0;
data d = new data();
for (i = 0; ; i++) {
Random random = new Random();
d.a[i] = random.nextInt(100);
}
mythread t1 = new mythread(1, d);
mythread t2 = new mythread(2, d);
mythread t3 = new mythread(3, d);
t1.start();
t2.start();
t3.start();
while (!(d.ifcomplete[0] & d.ifcomplete[1] & d.ifcomplete[2])) {
}
if(d.ifcomplete[0] & d.ifcomplete[1] & d.ifcomplete[2]) {
finalsum = d.sums[0] + d.sums[1] + d.sums[2];
System.out.println(finalsum);
}
for(i=0;;i++){
mysum=mysum+d.a[i];
}
System.out.println("sum is "+mysum);
}
}
class mythread extends Thread {
int no;
data datas;
mythread(int No, data d) {
no = No;
datas = d;
}
@Override
public synchronized void run() {
int sum = 0, i;
for (i = 0; i < 100; i++) {
sum = sum + datas.a[100 * (no - 1) + i];
}
datas.sums[no - 1] = sum;
datas.ifcomplete[no - 1] = true;
}
}
class data {
int[] a = new int[300];
boolean ifcomplete[] = new boolean[]{false, false, false};
int[] sums = new int[3];
}