import java.util.ArrayList;
import java.util.List;
/**
* 一个包含了2千个整数的数组,分拆了多个线程来进行并行计算,最后汇总出计算的结果。
*
*
* @author Zhouzilong
* @date 2019年8月12日
*/
public class P2 {
public static void main(String[] args) throws InterruptedException {
int arrayLength = 2000;
int[] a = new int[arrayLength];
int threadNum = 5;
int avg = arrayLength / threadNum;
int sum = 0;
List<MyThread> list = new ArrayList<MyThread>();
//给数组赋值
for (int i = 0; i < a.length; i++) {
a[i] = i;
}
//循环创建并开启线程,并且把线程对象放入集合中
for (int i = 0; i < threadNum; i++) {
MyThread m = new MyThread(a, i * avg, (i + 1) * avg);
m.start();
list.add(m);
//不能在这个循环中join,会变成串行。
}
/**
* 将所有5个子线程都插队到主线程前面完成。
Java多个线程计算数组中数字之和并输出最终结果
最新推荐文章于 2023-04-23 10:46:45 发布