「Java入門」スレッド毎のパラメータ値を保持するThreadLocalの使い方

Javaコード:
public class LocalthreadTest {
private static ThreadLocal<Integer> seqTdNum = new ThreadLocal<Integer>() {
public Integer initialValue() {
return 0;
}
};

public int getNextNum() {
seqTdNum.set(seqTdNum.get() + 1);
return seqTdNum.get();

}

public static void main(String[] args) {
LocalthreadTest tm = new LocalthreadTest();
SampleClient t1 = new SampleClient(tm);
SampleClient t2 = new SampleClient(tm);
SampleClient t3 = new SampleClient(tm);
t1.start();
t2.start();
t3.start();
}

private static class SampleClient extends Thread {
private LocalthreadTest ltd;

public SampleClient(LocalthreadTest ltd) {
this.ltd = ltd;
}

public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(“thread[” + Thread.currentThread().getName() + “] –> tm[” + ltd.getNextNum() + “]”);

}
}
}
}
実行結果:
thread[Thread-0] –> tm[1]
thread[Thread-1] –> tm[1]
thread[Thread-2] –> tm[1]
thread[Thread-1] –> tm[2]
thread[Thread-0] –> tm[2]
thread[Thread-1] –> tm[3]
thread[Thread-2] –> tm[2]
thread[Thread-0] –> tm[3]
thread[Thread-2] –> tm[3]

Comments are closed.