コンカレンシーユーティリティの練習

10スレッド同時実行して、スレッド間の分布を見るサンプルです。
単にjava.util.concurrentパッケージを使ってみたかっただけですw。

public static void main(String[] args) throws InterruptedException {
    int max = 10000;

    final CountDownLatch start = new CountDownLatch(1);
    final CountDownLatch end = new CountDownLatch(max);

    final Map<String, Integer> map = new HashMap<String, Integer>();

    ExecutorService executor = Executors.newFixedThreadPool(10);
    try {
        for (int i = 0; i < max; i++) {
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        start.await();    // スタートの合図を待つ

                        String threadName = Thread.currentThread().getName();
                        int count = map.containsKey(threadName) ? map.get(threadName) + 1 : 1;
                        map.put(threadName, count);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        end.countDown();    // スレッド終了の合図
                    }
                }
            });
        }

        start.countDown();    // スタートの合図

        end.await();        // 全ての終了を待って最後に結果発表
        
        for (String key : new TreeSet<String>(map.keySet())) {
            System.out.printf("%s \t: %d\n", key, map.get(key));
        }
    } finally {
        executor.shutdown();
    }
}

実行結果は毎回変わるのですが、以下は比較的ばらけた方。

pool-1-thread-1 : 42
pool-1-thread-10 : 3791
pool-1-thread-2 : 1
pool-1-thread-3 : 1
pool-1-thread-4 : 1
pool-1-thread-5 : 1
pool-1-thread-6 : 1
pool-1-thread-7 : 1
pool-1-thread-8 : 4348
pool-1-thread-9 : 1813

10,000回も実行しているのに1回しか実行されないスレッドがあるなんて。