编写代码, 实现多线程数组求和
问题:
1.给定一个很长的数组 (长度 1000w), 通过随机数的方式生成 1-100 之间的整数.
2.实现代码, 能够创建两个线程, 对这个数组的所有元素求和.
3.其中线程1 计算偶数下标元素的和, 线程2 计算奇数下标元素的和.
4.最终再汇总两个和, 进行相加
5.记录程序的执行时间.
代码:
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* 课后题:实现大数组相加
*/
public class ThreadDemo15 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//记录开始执行的时间
long stime=System.currentTimeMillis();
int[] arrs=new int[10000000];
//1、使用随机数初始化数组
Random random=new Random();
for (int i = 0; i <arrs.length ; i++) {
arrs[i]=(1+random.nextInt(100));
}
//2.创建两个线程执行相加操作
//2.1返回偶数之和
FutureTask<Integer> task1=new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int temp=0;
for (int i = 0; i <arrs.length ; i=i+2) {
temp +=arrs[i];
}
System.out.println("线程1:"+temp);
return temp;
}
});
Thread t1=new Thread(task1);
t1.start();
//2.2返回奇数之和
FutureTask<Integer> task2=new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int temp=0;
for (int i = 1; i <arrs.length ; i=i+2) {
temp += arrs[i];
}
System.out.println("线程2:"+temp);
return temp;
}
});
Thread t2=new Thread(task2);
t2.start();
//get方法需要得到线程的返回值,当线程执行完才能有返回值,因此,如果使用的带返回
//值的线程创建方式,是不需要加join等待线程执行完的。
int sum= task1.get()+task2.get();
System.out.println("最终结果:"+sum);
//记录一下执行完成的时间
long etime=System.currentTimeMillis();
//使用结束时间-开始时间=执行时间
System.out.println("最终执行时间:"+(etime-stime));
}
}