ThreadLocal

ThreadLocalを使ってみる。
名前の通り、Thread毎に値を保持できる。らしい。


てきとーにさわってみる。


public class TLTest2 extends Thread {

private static ThreadLocal tl = new ThreadLocal();

public static void main(String[] args) {
for (int i = 0; i < 10 ; i++) {
Thread test2 = new TLTest2(i);
test2.start();
try {
Thread.sleep(200);
} catch (InterruptedException ignore) {
}
}
}

private int count;

public TLTest2(int i) {
this.count = i;
}

public void run() {
String threadName = Thread.currentThread().getName();
Integer value = new Integer(count);
tl.set(value);
System.out.println("set: " + threadName + ": " + value);

int time = new Random().nextInt(2000);
try {
Thread.sleep(time);
} catch (InterruptedException ignore) {
}

Object result = tl.get();
System.out.println("get: " + threadName + ": " + result);

// なんとなく。
if (value != result) {
throw new IllegalStateException();
}
}

}

実行結果。

set: Thread-0: 0
set: Thread-1: 1
set: Thread-2: 2
set: Thread-3: 3
set: Thread-4: 4
get: Thread-3: 3
set: Thread-5: 5
get: Thread-2: 2
get: Thread-0: 0
get: Thread-1: 1
set: Thread-6: 6
get: Thread-5: 5
get: Thread-6: 6
set: Thread-7: 7
set: Thread-8: 8
set: Thread-9: 9
get: Thread-9: 9
get: Thread-4: 4
get: Thread-8: 8
get: Thread-7: 7
set、getが混ざっても、自分で設定した値がちゃんと取得できてる。
ただそれだけ。


ソースを追ってくと、実はThreadクラスがフィールドで持っている
ThreadLocal.ThreadLocalMapってやつで値を保持してるだけ。