ThreadLocal学习备忘

思路:
 
java 代码
  1. public class ThreadLocal   
  2.   
  3. {   
  4.   
  5. private Map values = Collections.synchronizedMap(new HashMap());   
  6.   
  7. public Object get()   
  8.   
  9. {   
  10.   
  11. Thread curThread = Thread.currentThread();   
  12.   
  13. Object o = values.get(curThread);   
  14.   
  15. if (o == null && !values.containsKey(curThread))   
  16.   
  17. {   
  18.   
  19. o = initialValue();   
  20.   
  21. values.put(curThread, o);   
  22.   
  23. }   
  24.   
  25. return o;   
  26.   
  27. }   
  28.   
  29. public void set(Object newValue)   
  30.   
  31. {   
  32.   
  33. values.put(Thread.currentThread(), newValue);   
  34.   
  35. }   
  36.   
  37. public Object initialValue()   
  38.   
  39. {   
  40.   
  41. return null;   
  42.   
  43. }   
  44.   
  45. }   
  46.   
  47.     

使用:

如果希望线程局部变量初始化其它值,那么需要自己实现ThreadLocal的子类并重写该方法,通常使用一个内部匿名类对ThreadLocal进行子类化,比如下面的例子,SerialNum类为每一个类分配一个序号

java 代码
  1. public class SerialNum   
  2.   
  3. {   
  4.   
  5. // The next serial number to be assigned   
  6.   
  7. private static int nextSerialNum = 0;   
  8.   
  9. private static ThreadLocal serialNum = new ThreadLocal()   
  10.   
  11. {   
  12.   
  13. protected synchronized Object initialValue()   
  14.   
  15. {   
  16.   
  17. return new Integer(nextSerialNum++);   
  18.   
  19. }   
  20.   
  21. };   
  22.   
  23. public static int get()   
  24.   
  25. {   
  26.   
  27. return ((Integer) (serialNum.get())).intValue();   
  28.   
  29. }   
  30.   
  31. }   

 SerialNum类的使用将非常地简单,因为get()方法是static的,所以在需要获取当前线程的序号时,简单地调用:

int serial = SerialNum.get();

即可。

 

总结:

当然ThreadLocal并不能替代同步机制,两者面向的问题领域不同。同步机制是为了同步多个线程对相同资源的并发访问,是为了多个线程之间进行通信的有效方式;而ThreadLocal是隔离多个线程的数据共享,从根本上就不在多个线程之间共享资源(变量),这样当然不需要对多个线程进行同步了。所以,如果你需要进行多个线程之间进行通信,则使用同步机制;如果需要隔离多个线程之间的共享冲突,可以使用ThreadLocal,这将极大地简化你的程序,使程序更加易读、简洁。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值