第6章 並行処理の機能強化 : 問題 4 : LongAccumulator
問題
LongAccumulator
を使用して、要素の最大値あるいは最小値を計算せよ
解答
1000万個の配列を用意して、最大値を求めてみる
■ 準備
long[] values = new long[1000_0000]; for (int i = 0; i < values.length; i++) { values[i] = (long)(1000_0000 * Math.random()); }
■ シングルスレッド版
long max = Long.MIN_VALUE; for (int i = 0; i < values.length; i++) { max = Math.max(values[i], max); } System.out.println("最大値 : " + max);
1000個のスレッドで分担して最大値を求める
■ LongAccumulator
final int TASK = 1000; final int COUNT = 10000; LongAccumulator max = new LongAccumulator(Math::max, Long.MIN_VALUE); CountDownLatch latch = new CountDownLatch(TASK); ExecutorService pool = Executors.newCachedThreadPool(); for (int n = 0; n < TASK; n++) { int start = COUNT * n; int end = Math.min(start + COUNT, values.length); pool.submit( () -> { for (int i = start; i < end; i++) { max.accumulate(values[i]); } latch.countDown(); } ); } pool.shutdown(); latch.await(); System.out.println("最大値 : " + max);