编写代码, 实现多线程数组求和

编写代码, 实现多线程数组求和

问题:

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));

    }
}

在这里插入图片描述

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZJHFOREVERZJ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值