Java並行処理プログラミング読了

JavaEE 勉強会のお題になっていたので読み始めたこの本ですが、とっても面白かったです。マルチスレッドとか、簡単なことしかやったことありませんでしたが、この本を読むと何かマルチスレッドを無駄に使いたくなります。

Java5で並行処理の為のライブラリがこんなに充実していたことも今更ながらに勉強になったので、読んで良かったです。勉強会自体に全然参加できなかったのは心残りでしたが。。。

せっかくなので、あとがきにあったお題をやってみました。こんな感じかなぁ?

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author jundu
 * 
 */
public class ThreadTest2 implements Runnable {

    private static final String[] jn = { "0", "1", "2", "3", "4", "5", "6",
            "7", "8", "9" };

    private int id;

    private String ids;

    private CountDownLatch latch;

    public ThreadTest2(int tid, CountDownLatch latch) {
        id = tid;
        ids = id < 10 ? jn[id] : String.valueOf(id);
        this.latch = latch;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Runnable#run()
     */
    public void run() {
        System.out.println(ids + "番のスレッドをスタートします");
        long stime = System.currentTimeMillis();
        for (int i = 0; i < 20000; ++i) {
            for (int j = 0; j < 20000; ++j) {
                double p = i * j;
                p = Math.sqrt(p);
            }
        }
        stime = System.currentTimeMillis() - stime;
        System.out.println(ids + "番のスレッドは" + stime + "ミリ秒かかりました");
        latch.countDown();
    }

    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        if (args.length < 1) {
            System.out.println("使い方: java ThreadTest2 x");
            System.out.println("xでスレッド数を指定してください。");
            System.exit(1);
        }

        int cpu = Integer.parseInt(args[0]);

        ExecutorService exec = Executors.newFixedThreadPool(cpu);
        CountDownLatch latch = new CountDownLatch(cpu);
        for (int i = 0; i < cpu; ++i) {
            exec.execute(new ThreadTest2(i, latch));
        }
        latch.await();
        exec.shutdown();
    }

}