代码清单:
- public class SequenceNumber {
- //通过匿名内部类覆盖ThreadLocal的initialValue()方法,指定初始值
- private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>(){
- public Integer initialValue(){
- return 0;
- }
- };
- //获取下一个序列值
- public int getNextNum(){
- seqNum.set(seqNum.get()+1);
- return seqNum.get();
- }
- public static void main(String[] args){
- SequenceNumber sn = new SequenceNumber();
- TestClient t1 = new TestClient(sn);
- TestClient t2 = new TestClient(sn);
- TestClient t3 = new TestClient(sn);
- t1.start();
- t2.start();
- t3.start();
- }
- }
- public class TestClient extends Thread{
- private SequenceNumber sn;
- public TestClient(SequenceNumber sn){
- this.sn = sn;
- }
- public void run(){
- for(int i=0;i<3;i++){
- System.out.println("Thread"+Thread.currentThread().getName()+":"+sn.getNextNum());
- }
- }
- }
输出结果:
ThreadThread-0:1
ThreadThread-1:1
ThreadThread-1:2
ThreadThread-1:3
ThreadThread-0:2
ThreadThread-0:3
ThreadThread-2:1
ThreadThread-2:2
ThreadThread-2:3
考察输出的结果信息,我们发现每个线程所产生的序号虽然都共享同一个SequenceNumber实例,但它们并没有发生相互干扰的情况,而是各自产生独立的序列号,这是因为我们通过ThreadLocal为每一个线程提供了单独的副本。