ThreadLocal总结

来源:互联网 发布:mac轻量级虚拟机 编辑:程序博客网 时间:2024/06/07 00:37

碰到ThreadLocal时,我们需要这样考虑:

1.什么是ThreadLocal

2.为什么使用ThreadLocal

3.怎么用ThreadLocal

4.优点缺点总结

1.什么是ThreadLocal

java提供了ThreadLocal这个类型,具有该类型的成员变量,每个线程都可以保留一份它的备份数据,通过set方法设置;在线程内部用get方法获取自己备份的数据。这个备份并不是JVM自己备份的,而是通过ThreadLocal的set方法完成的,它的本质是以当前线程的Id为key,存储该线程的数据。如果每个线程set的值都没有关联,那么这个成员的值肯定是线程安全的;但是如果两个线程在set时引用了同一个数据,那么就仍然会存在同步问题。

很抽象。。。。。
待会我们还是看看例子吧。。。

2.为什么使用ThreadLocal

ThreadLocal既然能解决并发出现的问题,那我们之前经常使用的synchronized或者volatile有什么区别呢。synchronized这类线程同步的机制可以解决多线程并发问题,在这种解决方案下,多个线程访问到的, 都是同一份变量的内容。为了防止在多线程访问的过程中,可能会出现并发错误。 不得不对多个线程的访问进行同步,这样也就意味着, 多个线程必须先后对变量的值进行访问或者修改,这是一种以延长访问时间来换取线程安全性的策略。而ThreadLocal类为每一个线程都维护了自己独有的变量拷贝。每个线程都拥有了自己独立的一个变量,竞争条件被彻底消除了,那就没有任何必要对这些线程进行同步,它们也能最大限度的由CPU调度,并发执行。并且由于每个线程在访问该变量时,读取和修改的,都是自己独有的那一份变量拷贝,变量被彻底封闭在每个访问的线程中,并发错误出现的可能也完全消除了。对比前一种方案,这是一种以空间来换取线程安全性的策略。

3.怎么使用ThreadLocal呢。

import java.util.Date;  public class MyThreadLocal {      private ThreadLocal date = new ThreadLocal();      private Date d = null;      public void process(){          if(date.get()==null){              date.set(new Date());              System.out.println("thread local fileld:"+date.get());          }      }      //操作普通成员,需要同步处理      public void p(){          synchronized(MyThreadLocal.class){              if(d==null){                  d = new Date();                  System.out.println("ordinary field:"+d);              }          }      }  

测试类:定义一个MyThreadLocal对象实例,由5个线程同时访问它的方法。

 import java.util.Date;      public class Test {          public static void main(String[] args) {              final MyThreadLocal t = new MyThreadLocal();              for(int i = 0;i<5;i++){                  Thread thread = new Thread(){                      public void run(){                          t.process();                          t.p();                      }                  };                  thread.start();              }              Date d1 = new Date();              Date d2 = new Date();              System.out.println(d1==d2);              System.out.println(d1.hashCode()==d2.hashCode());          }      }  测试结果:    false      true      thread local fileld:Fri Apr 10 14:47:30 CST 2015      ordinary field:Fri Apr 10 14:47:31 CST 2015      thread local fileld:Fri Apr 10 14:47:30 CST 2015      thread local fileld:Fri Apr 10 14:47:30 CST 2015      thread local fileld:Fri Apr 10 14:47:30 CST 2015      thread local fileld:Fri Apr 10 14:47:30 CST 2015  

测试结果分析:很显然共享的成员变量d只被一个线程初始化了一次,
所以p方法的代码只执行了一次;而ThreadLocal成员变量,每个访问该变量的线程都会自己创建一个备份数据,process方法被执行了五次。此外,还发现两次new Date()得到的对象的hashCode很容易相等,但的确是两个不同对象
那么我们能不能模拟一个ThreadLocal呢。

SimpleThreadLocalpublic class SimpleThreadLocal {private Map valueMap = Collections.synchronizedMap(new HashMap());public void set(Object newValue) {valueMap.put(Thread.currentThread(), newValue);①键为线程对象,值为本线程的变量副本}public Object get() {Thread currentThread = Thread.currentThread();Object o = valueMap.get(currentThread);②返回本线程对应的变量if (o == null && !valueMap.containsKey(currentThread)) {③如果在Map中不存在,放到Map中保存起来。o = initialValue();valueMap.put(currentThread, o);}return o;}public void remove() {valueMap.remove(Thread.currentThread());}public Object initialValue() {return null;}}

再看看Thread的源码。。

那么到底ThreadLocal类是如何实现这种“为每个线程提供不同的变量拷贝”的呢?先来看一下ThreadLocal的set()方法的源码是如何实现的:

/**     * Sets the current thread's copy of this thread-local variable     * to the specified value.  Most subclasses will have no need to      * override this method, relying solely on the {@link #initialValue}     * method to set the values of thread-locals.     *     * @param value the value to be stored in the current thread's copy of     *        this thread-local.     */    public void set(T value) {        Thread t = Thread.currentThread();        ThreadLocalMap map = getMap(t);        if (map != null)            map.set(this, value);        else            createMap(t, value);    }

没有什么魔法,在这个方法内部我们看到,首先通过getMap(Thread t)方法获取一个和当前线程相关的ThreadLocalMap,然后将变量的值设置到这个ThreadLocalMap对象中,当然如果获取到的ThreadLocalMap对象为空,就通过createMap方法创建。

线程隔离的秘密,就在于ThreadLocalMap这个类。ThreadLocalMap是ThreadLocal类的一个静态内部类,它实现了键值对的设置和获取(对比Map对象来理解),每个线程中都有一个独立的ThreadLocalMap副本,它所存储的值,只能被当前线程读取和修改。ThreadLocal类通过操作每一个线程特有的ThreadLocalMap副本,从而实现了变量访问在不同线程中的隔离。因为每个线程的变量都是自己特有的,完全不会有并发错误。还有一点就是,ThreadLocalMap存储的键值对中的键是this对象指向的ThreadLocal对象,而值就是你所设置的对象了。

为了加深理解,我们接着看上面代码中出现的getMap和createMap方法的实现:

ThreadLocalMap getMap(Thread t) {        return t.threadLocals;    }void createMap(Thread t, T firstValue) {        t.threadLocals = new ThreadLocalMap(this, firstValue);    }

代码已经说的非常直白,就是获取和设置Thread内的一个叫threadLocals的变量,而这个变量的类型就是ThreadLocalMap,这样进一步验证了上文中的观点:每个线程都有自己独立的ThreadLocalMap对象。打开java.lang.Thread类的源代码,我们能得到更直观的证明:

/* ThreadLocal values pertaining to this thread. This map is maintained     * by the ThreadLocal class. */    ThreadLocal.ThreadLocalMap threadLocals = null;

那么接下来再看一下ThreadLocal类中的get()方法,代码是这么说的:

/**     * Returns the value in the current thread's copy of this     * thread-local variable.  If the variable has no value for the     * current thread, it is first initialized to the value returned     * by an invocation of the {@link #initialValue} method.     *     * @return the current thread's value of this thread-local     */    public T get() {        Thread t = Thread.currentThread();        ThreadLocalMap map = getMap(t);        if (map != null) {            ThreadLocalMap.Entry e = map.getEntry(this);            if (e != null)                return (T)e.value;        }        return setInitialValue();    }    /**     * Variant of set() to establish initialValue. Used instead     * of set() in case user has overridden the set() method.     *     * @return the initial value     */    private T setInitialValue() {        T value = initialValue();        Thread t = Thread.currentThread();        ThreadLocalMap map = getMap(t);        if (map != null)            map.set(this, value);        else            createMap(t, value);        return value;    }

这两个方法的代码告诉我们,在获取和当前线程绑定的值时,ThreadLocalMap对象是以this指向的ThreadLocal对象为键进行查找的,这当然和前面set()方法的代码是相呼应的。

进一步地,我们可以创建不同的ThreadLocal实例来实现多个变量在不同线程间的访问隔离,为什么可以这么做?因为不同的ThreadLocal对象作为不同键,当然也可以在线程的ThreadLocalMap对象中设置不同的值了。通过ThreadLocal对象,在多线程中共享一个值和多个值的区别,就像你在一个HashMap对象中存储一个键值对和多个键值对一样,仅此而已。

4.优点缺点总结

ThreadLocal是解决线程安全问题一个很好的思路,它通过为每个线程提供一个独立的变量副本解决了变量并发访问的冲突问题。在很多情况下,
ThreadLocal比直接使用synchronized同步机制解决线程安全问题更简单,更方便,且结果程序拥有更高的并发性。
最后再提一句,ThreadLocal变量的这种隔离策略,
也不是任何情况下都能使用的。如果多个线程并发访问的对象实例只允许,
也只能创建那么一个,那就没有别的办法了,老老实实的使用同步机制来访问吧。

我创建了一个微信公众号,共同学习和交流android技术。欢迎订阅。

扫码,或者手动输入 : androidesigner 查找公众号并加我为关注。

二维码

0 0
原创粉丝点击