思路:
java 代码
- public class ThreadLocal
- {
- private Map values = Collections.synchronizedMap(new HashMap());
- public Object get()
- {
- Thread curThread = Thread.currentThread();
- Object o = values.get(curThread);
- if (o == null && !values.containsKey(curThread))
- {
- o = initialValue();
- values.put(curThread, o);
- }
- return o;
- }
- public void set(Object newValue)
- {
- values.put(Thread.currentThread(), newValue);
- }
- public Object initialValue()
- {
- return null;
- }
- }
使用:
如果希望线程局部变量初始化其它值,那么需要自己实现ThreadLocal的子类并重写该方法,通常使用一个内部匿名类对ThreadLocal进行子类化,比如下面的例子,SerialNum类为每一个类分配一个序号
java 代码
- public class SerialNum
- {
- // The next serial number to be assigned
- private static int nextSerialNum = 0;
- private static ThreadLocal serialNum = new ThreadLocal()
- {
- protected synchronized Object initialValue()
- {
- return new Integer(nextSerialNum++);
- }
- };
- public static int get()
- {
- return ((Integer) (serialNum.get())).intValue();
- }
- }
SerialNum类的使用将非常地简单,因为get()方法是static的,所以在需要获取当前线程的序号时,简单地调用:
int serial = SerialNum.get();
即可。
总结:
当然ThreadLocal并不能替代同步机制,两者面向的问题领域不同。同步机制是为了同步多个线程对相同资源的并发访问,是为了多个线程之间进行通信的有效方式;而ThreadLocal是隔离多个线程的数据共享,从根本上就不在多个线程之间共享资源(变量),这样当然不需要对多个线程进行同步了。所以,如果你需要进行多个线程之间进行通信,则使用同步机制;如果需要隔离多个线程之间的共享冲突,可以使用ThreadLocal,这将极大地简化你的程序,使程序更加易读、简洁。