> 谈到线程正好问个问题。
>
> 在jdk1.2中有一个threadLocal类,不知道大家用过没有。
> 以下是jdk的doc给出的注释。
> This class provides thread-local variables. These
> variables differ from their normal counterparts in
> that each thread that accesses one (via its get or
> set method) has its own, independently initialized
> copy of the variable. ThreadLocal instances are
> typically private static fields in classes that wish
> to associate state with a thread (e.g., a user ID or
> Transaction ID).
>
> For example, in the class below, the private static
> ThreadLocal instance (serialNum) maintains a "serial
> number" for each thread that invokes the class's
> static SerialNum.get() method, which returns the
> current thread's serial number. (A thread's serial
> number is assigned the first time it invokes
> SerialNum.get(), and remains unchanged on subsequent
> calls.)
>
> public class SerialNum {
> // The next serial number to be assigned
> private static int nextSerialNum = 0;
>
> private static ThreadLocal serialNum = new
> new ThreadLocal() {
> protected synchronized Object initialValue()
> lValue() {
> return new Integer(nextSerialNum++);
> }
> };
>
> public static int get() {
> return ((Integer)
> Integer) (serialNum.get())).intValue();
> }
> }
>
> Each thread holds an implicit reference to its copy
> of a thread-local variable as long as the thread is
> alive and the ThreadLocal instance is accessible;
> after a thread goes away, all of its copies of
> thread-local instances are subject to garbage
> collection (unless other references to these copies
> exist).
>
> 1 这样不就是意味着类中私有的static
> fields是线程安全的。
> 2 他的性能到底如何?
>
fields也不是很安全,从某个角度来说增加性能的时候牺牲了安全性和封装
ThreadLocal大多用做共享数据,比如有人在hibernate中使用它来模拟持久bean的共享性