ThreadLocal

相关连接:多线程

  http://www.jianshu.com/p/a8fa72e708d3less

 

  建立Handler的时候,须要先建立当前线程的Looper,Android默认在启动的时候为咱们建立的  主线程的Looper,因此咱们能够在主线程直接建立Handler。async

  可是在子线程建立Handler的时候,咱们必须先手动建立Looper,才能建立Handler,不然会抛出一个必须调用Looper.prepare()的异常信息。ide

  缘由:      oop

public Handler(Callback callback, boolean async) {
  //省略

  mLooper = Looper.myLooper();
  if (mLooper == null) {
      throw new RuntimeException(
          "Can't create handler inside thread that has not called Looper.prepare()");
  }
  //省略
}

  问题:ui

    相同的代码,为何在主线程建立就能够,在子线程建立就异常???为何在子线程中,经过Looper.myLooper()方法获取的就是为空呢?this

  查看Looper.myLooper()源码,可知道缘由:ThreadLocal获取的是“当前线程”的Looperspa

sThreadLocal.get();

  ThreadLocal在何时set值的那?--- 在Looper中源码中线程

private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
        throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper(quitAllowed));
}

  ThreadLocal的初始化:--- 在Looper中源码中code

    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

    看注释能够知道,sThreadLocal.get()以前,必须Looper.prepare(),不然get到的值为null。

 

ThreadLocal是什么? 

    看一下官方的解释:

Implements a thread-local storage, that is, a variable for which each thread
has its own value. All threads share the same {@code ThreadLocal} object,
but each sees a different value when accessing it, and changes made by one
thread do not affect the other threads. The implementation supports
{@code null} values.

    意思是说:ThreadLocal实现与线程相关的存储。全部线程共享一个ThreadLocal对象,可是不一样的线程有本身的值。而且当一个线程的值发生改变以后,不会影响其余的线程的值。

      因此这就解释了为何 在子线程中,若是不Looper.prepare()就直接建立Handler的时候,会抛出异常。

 

ThreadLocal并非线程,它的做用是能够在每一个线程中存储数据,,数据存储之后,只有在指定线程中能够获取到存储的数据。对于其它线程来讲没法获取到数据。
ThreadLocal是一个关于建立线程局部变量的类。一般状况下,咱们建立的变量是能够被任何一个线程访问并修改的。而使用ThreadLocal建立的变量只能被当前线程访问,其余线程则没法访问和修改。

 

下面看一下ThreadLocal部分源码:

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);//建立当前线程的map(仅第一次调用)
    }

    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);//this表明的是ThreadLocal
    }

    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();//null
    }


    private T setInitialValue() {
        T value = initialValue();//null
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

    protected T initialValue() {
        return null;
    }

   全部线程共用一个ThreadLocal,每个线程都有一个ThreadLocalMap,key为当前线程的ThreadLocal。

 

  因此从此,若是多线程的每个线程都有一个相同变量,可是每一个线程的变量值只有当前线程本身能够修改,不受其它线程的影响,那么你就能够用ThreadLocal。多线程共享同一个ThreadLocal对象。    

相关文章
相关标签/搜索