多线程Callable优化for循环,需要拿到for循环的返回值

package com;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThread {


    public static void main(String[] args) throws Exception {


        long start = System.currentTimeMillis();
        int all = test1();
        long end = System.currentTimeMillis();
        System.out.println("all的值为:" + all);
        System.out.println("耗时秒:" + (end - start) / 1000);

        long start2 = System.currentTimeMillis();
        int all2 = test2();
        long end2 = System.currentTimeMillis();
        System.out.println("all2的值为:" + all2);
        System.out.println("2耗时秒:" + (end2 - start2) / 1000);

    }


    /**
     * 不用多线程的方法测试
     *
     * @return
     * @throws InterruptedException
     */
    private static int test1() throws InterruptedException {
        int all = 0;
        for (int i = 0; i < 20; i++) {
            //这里模拟业务和耗时操作
            Thread.sleep(500);
            all = all + i;
        }
        return all;
    }

    /**
     * 用了多线程的方法测试
     *
     * @return
     * @throws InterruptedException
     * @throws InterruptedException
     * @throws ExecutionException
     */
    private static int test2() throws InterruptedException, InterruptedException, ExecutionException {

        ExecutorService service = Executors.newFixedThreadPool(10);
        ArrayList<Future<Integer>> list = new ArrayList<>();

        for (int i = 0; i < 20; i++) {
            CallableTest callableTest = new CallableTest(i);
            list.add(service.submit(callableTest));
        }

        int all = 0;
        for (Future<Integer> dateFuture : list) {
            all = all + dateFuture.get();
        }
        return all;
    }


}
package com;

import java.util.concurrent.Callable;

public class CallableTest implements Callable {


    int i;

    CallableTest(int sort){
        i=sort;
    }

    @Override
    public Object call() throws Exception {
        //这里模拟业务和耗时操作
        Thread.sleep(500);
        return i;
    }

}

运行结果:结果都获取到了,且一样;多线程优化完后只要1秒,不用多线程要10秒

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值