标签:number wait 长度 code bnu system col Fix nts
有一个大小为50000的数组,要求开启5个线程分别计算10000个元素的和,然后累加得到总和
public class Test5 { private static Random random = new Random(); public static void main(String[] args) { //数组大小 int size = 50000; //定义数组 int[] numbers = new int[size]; //随机初始化数组 for (int i = 0; i < size; i++) { numbers[i] = random.nextInt(100); } //单线程计算结果 System.out.println(); Long sum = 0L; for (int i = 0; i < size; i++) { sum += numbers[i]; } System.out.println("单线程计算结果:" + sum); //多线程计算结果 //定义线程池 ExecutorService executorService = Executors.newFixedThreadPool(5); //定义长度为5的数组保存每个线程的计算结果 final int[] results = new int[5]; //定义一个大小为5的循环栅栏 CyclicBarrier barrier = new CyclicBarrier(5, () -> { long sums = 0; for (int i = 0; i < 5; i++) { sums += results[i]; } System.out.println("多线程计算结果:" + sums); }); //子数组长度 int length = 10000; //定义五个线程去计算 for (int i = 0; i < 5; i++) { //定义子数组 int[] subNumbers = Arrays.copyOfRange(numbers, (i * length), ((i + 1) * length)); //盛放计算结果 int finalI = i; executorService.submit(() -> { for (int j = 0; j < subNumbers.length; j++) { results[finalI] += subNumbers[j]; } //等待其他线程进行计算 try { barrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }); } //关闭线程池 executorService.shutdown(); } }
标签:number wait 长度 code bnu system col Fix nts
原文地址:https://www.cnblogs.com/moris5013/p/11871123.html