public class Sequence {
private static ThreadLocal<Integer> localVar = new ThreadLocal<Integer>() {
public Integer initialValue() {
return 0;
}
};
public int getNextVal() {
localVar.set(localVar.get() + 1);
return localVar.get();
}
public static void main(String[] args) {
Sequence seq = new Sequence();
Client client1 = new Client(seq);
Client client2 = new Client(seq);
Client client3 = new Client(seq);
client1.start();
client2.start();
client3.start();
}
}
package hvp.spring.transaction.threadLocal;
public class Client extends Thread{
private Sequence seq;
public Client(Sequence seq){
this.seq = seq;
}
public void run(){
StringBuffer sb = new StringBuffer();
for(int i=0;i<5;i++){
sb.append("Thread[");
sb.append(Thread.currentThread().getName());
sb.append("] seq[");
sb.append(seq.getNextVal());
sb.append("]");
System.out.println(sb.toString());
sb.delete(0, sb.length());
}
}
}