複数スレッドで平行処理し、順序そのままで結果を格納する
こんにちわ、猫好きリーマンのほげPGです。 今回は複数スレッドで平行処理し、要求時の順序で結果を配列に格納するコードを紹介します。 ソースコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.Collectors; public class Hoge { public static void main(String[] args) throws Exception { log("start ..."); ExecutorService streamPool = Executors.newFixedThreadPool(10); //① List<String> requests = Arrays.asList(new String[] {"11", "22", "33", "44", "55"}); //② String[] array = new String[requests.size()]; //③ try { CountDownLatch latch = new CountDownLatch(requests.size()); //④ int i = 0; for (String val : requests) { Integer x = i++; //⑤ streamPool.submit(() -> { //⑥ log("start..." + x); try { array[x] = doHoge(val); //⑦ } catch (Exception e) { log(e.toString()); } finally { latch.countDown(); } log("end..." + x); }); } latch.await(); } finally { streamPool.shutdown(); } List<String> results = Arrays.stream(array) .filter(pi -> pi != null) //⑧ .collect(Collectors.toList()); //⑨ log(results.toString()); log("end ..."); } static Random rand = new Random(); static String doHoge(String v) throws InterruptedException { if ("44".equals(v)) throw new RuntimeException("test"); int n = rand.nextInt(10); Thread.sleep(n * 1000); return v + "-" + n; } public static void log(String msg) { System.out.println(msg); } } |