通过多个线程计算1到50000相加之和-java篇

1.通过cyclicBarrier来计算,原则是启动五个线程,然后等待都完成,然后输出结果

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: 张小乙
 * @Date: 2019/2/4 15:29
 * @Version: 1.0
 * @Description: 1.0
 */
public class CyclicBarrierTest {

    public final static int[] SUMS_ARRAY = new int[5];


    public static class Number implements Runnable {

        private int[] array;

        private int start;

        private int end;

        private int batch;

        private CyclicBarrier cyclicBarrier;

        public Number(int[] array, int start, int end, int batch, CyclicBarrier cyclicBarrier) {
            this.array = array;
            this.start = start;
            this.end = end;
            this.batch = batch;
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            int sums = 0;
            for (int i = start; i < end; i++) {
                sums += array[i];
            }
            SUMS_ARRAY[batch] = sums;
            System.out.println(Thread.currentThread().getName() + ",SUMS_ARRAY:" + sums);
            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        int[] array = new int[50000];
        for (int i = 0; i < array.length; i++) {
            array[i] = i;
        }

        AtomicInteger sums = new AtomicInteger(0);
        AtomicBoolean isFinish = new AtomicBoolean(false);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> {
            for (int i = 0; i < SUMS_ARRAY.length; i++) {
                sums.addAndGet(SUMS_ARRAY[i]);
            }
            isFinish.set(true);
            System.out.println("总和为:" + sums);
        });

        int corePoolSize = 5;
        int maximumPoolSize = 5;
        long keepAliveTime = 0l;
        final RejectedExecutionHandler defaultHandler =
                new ThreadPoolExecutor.AbortPolicy();

        ExecutorService executorService = new ThreadPoolExecutor(corePoolSize,
                                                                 maximumPoolSize,
                                                                 keepAliveTime,
                                                                 TimeUnit.SECONDS,
                                                                 new LinkedBlockingQueue<>(),
                                                                 Executors.defaultThreadFactory(), defaultHandler);
        for (int i = 0; i < 5; i++) {
            Number number = new Number(array, (i) * 10000, (i + 1) * 10000 - 1, i, cyclicBarrier);
            executorService.execute(number);
        }

        while (true) {
            if (isFinish.get()) {
                System.out.println("总和2为:" + sums);
                break;
            }
        }
    }
}

2.通过Callable与Future方法

/**
 * @Author: 张小乙
 * @Date: 2019/2/12 15:22
 * @Version: 1.0
 * @Description: 1.0
 */
public class FutureTest {

    public final static int[] SUMS_ARRAY = new int[5];


    public static class Number implements Callable<Integer> {

        private int[] array;

        private int start;

        private int end;

        private int batch;

        public Number(int[] array, int start, int end, int batch) {
            this.array = array;
            this.start = start;
            this.end = end;
            this.batch = batch;
        }

        @Override
        public Integer call(){
            int sums = 0;
            for (int i = start; i < end; i++) {
                sums += array[i];
            }
            SUMS_ARRAY[batch] = sums;
            System.out.println(Thread.currentThread().getName() + ",SUMS_ARRAY:" + sums);
            return sums;
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
        int[] array = new int[50000];
        for (int i = 0; i < array.length; i++) {
            array[i] = i;
        }

        int corePoolSize = 5;
        int maximumPoolSize = 5;
        long keepAliveTime = 0l;
        final RejectedExecutionHandler defaultHandler = new ThreadPoolExecutor.AbortPolicy();

        ExecutorService executorService = new ThreadPoolExecutor(corePoolSize,
                                                                 maximumPoolSize,
                                                                 keepAliveTime,
                                                                 TimeUnit.SECONDS,
                                                                 new LinkedBlockingQueue<>(),
                                                                 Executors.defaultThreadFactory(),
                                                                 defaultHandler);
        List<Future<Integer>> futureList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Number number = new Number(array, (i) * 10000, (i + 1) * 10000 - 1, i);
            Future<Integer> future = executorService.submit(number);
            futureList.add(future);
        }

        Integer sums = 0;
        for(Future<Integer> future : futureList){
            Integer amount = future.get(2000,TimeUnit.MILLISECONDS);
            sums+= amount;
        }
        System.out.println("房款总金额为sums:" + sums);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值