ThreadLocal というクラスを発見した

以下のような感じで使用する。

public class ThreadLocalTest {
	// これがスレッドローカル変数の原資
	private static int num = 0;

	// 実体はひとつしかないが、スレッド毎に異なる値を返す変数
	private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
		@Override
		protected synchronized Integer initialValue() {
			return num++;
		}
	};

	public static void main(String[] args) throws Exception {
		for (int i = 0; i < 10; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					// 各スレッドで何度呼び出してもユニークな値を返してくれる
					System.out.print(threadLocal.get() + " " + threadLocal.get() + "\n");
				}
			}).start();
		}
	}
}

結果は以下の通り。

0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9

スレッドをいちいちサブクラス化しなくてもよいのが便利だ。