ThreadLocal

ThreadLocal 是一个线程局部变量

static 公所周知静态的


如果研究过struts2的源码就大概可以知道

ActionContext本身就是一个 static ThreadLocal 类型

也正是static 跟 ThreadLocal的搭配导致我们可以在任何地方使用ActionContext,但是同时,不同的Action里的ActionContext又互相独立,有所不同


以下是转的一些简单实例

  1. public class SequenceNumber {  

  2.   

  3.  private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>(){  

  4.   public Integer initialValue(){  

  5.    return 0;  

  6.   }  

  7.  };  

  8.    

  9.  public int getNextNum(){  

  10.   seqNum.set(seqNum.get() + 1);  

  11.   return seqNum.get();  

  12.  }  

  13.    

  14.  public static void main(String[] args){  

  15.   SequenceNumber sn = new SequenceNumber();  

  16.   TestClient t1  = new TestClient(sn);  

  17.   TestClient t2  = new TestClient(sn);  

  18.   TestClient t3  = new TestClient(sn);  

  19.     

  20.   t1.start();  

  21.   t2.start();  

  22.   t3.start();  

  23.     

  24.   t1.print();  

  25.   t2.print();  

  26.   t3.print();  

  27.     

  28.     

  29.  }  

  30.    

  31.  private static class TestClient extends Thread{  

  32.   private SequenceNumber sn ;  

  33.   public TestClient(SequenceNumber sn ){  

  34.    this.sn = sn;  

  35.   }  

  36.     

  37.   public void run(){  

  38.    for(int i=0; i< 3; i++){  

  39.     System.out.println( Thread.currentThread().getName()  + " --> " + sn.getNextNum());  

  40.    }  

  41.   }  

  42.     

  43.   public void print(){  

  44.    for(int i=0; i< 3; i++){  

  45.     System.out.println( Thread.currentThread().getName()  + " --> " + sn.getNextNum());  

  46.    }  

  47.   }  

  48.  }  

  49.    

  50. }  

    运行完之后结果

  1. Thread-2 --> 1  

  2. Thread-2 --> 2  

  3. Thread-2 --> 3  

  4. Thread-0 --> 1  

  5. Thread-0 --> 2  

  6. Thread-0 --> 3  

  7. Thread-1 --> 1  

  8. Thread-1 --> 2  

  9. Thread-1 --> 3  

  10. main --> 1  

  11. main --> 2  

  12. main --> 3  

  13. main --> 4  

  14. main --> 5  

  15. main --> 6  

  16. main --> 7  

  17. main --> 8  

  18. main --> 9  


转载于:https://my.oschina.net/u/2445858/blog/504520

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值