美文网首页我爱编程
Android笔记——ThreadLocal原理浅析

Android笔记——ThreadLocal原理浅析

作者: wenzhihao123 | 来源:发表于2018-04-15 17:58 被阅读53次

    复习和回顾Android知识,梳理笔记

    ThreadLocal简介

    ThreadLocal一般在开发中不是很常见,但是了解过Android消息机制的应该都看过Handler及Looper的源码,在Looper源码里有出现过:

    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

    ThreadLocal源码给出的定义(英文翻译的有点渣):一个为线程本地提供数据的类,这些数据从每个线程获取到的都是不同的,每个线程独立初始化这些数据的副本。 简单来说就是ThreadLocal为不同线程存储数据,并且每个线程存储的数据是独立的,修改互不影响其他线程。

    举个栗子

    import android.os.Bundle;
    import android.support.annotation.Nullable;
    import android.support.v4.app.FragmentActivity;
    import android.util.Log;
    import player.video.wzh.com.videoplayer.R;
    
    public class ThreadLocalAct extends FragmentActivity {
        public String TAG = "wenzhihao";
        /**
         * 定义ThreadLocal
         */
        private ThreadLocal<Student> threadLocal = new ThreadLocal(){
            @Override
            protected Student initialValue() {
                return new Student("NULL");
            }
        };
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.act_threadlocal);
            /**
             * 在主线程设置一个对象
             */
            threadLocal.set(new Student("张三"));
            initTest();
        }
    
        private void initTest() {
            Log.e(TAG,Thread.currentThread().getName()+"-->"+threadLocal.get().toString());
            /**
             * 开启一个子线程获取Student
             */
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    Log.e(TAG,Thread.currentThread().getName()+"-->"+threadLocal.get().toString());
                }
            }.start();
            /**
             * 开启一个子线程再set一个Student
             */
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    threadLocal.set(new Student("丽丽"));
                    Log.e(TAG,Thread.currentThread().getName()+"-->"+threadLocal.get().toString());
                }
            }.start();
    
            Log.e(TAG,Thread.currentThread().getName()+"-->"+threadLocal.get().toString());
        }
    
        public class Student{
            public Student(String name) {
                this.name = name;
            }
            public String name ;
            public String getName() {
                return name;
            }
            public void setName(String name) {
                this.name = name;
            }
            @Override
            public String toString() {
                return "Student{" +
                        "name='" + name + '\'' +
                        '}';
            }
        }
    }
    
    

    运行结果(结果具有随机性,线程非顺序执行):

    E/wenzhihao: main---------Student{name='张三'}
    E/wenzhihao: Thread-1200---------Student{name='NULL'}
    E/wenzhihao: main---------Student{name='张三'}
    E/wenzhihao: Thread-1201---------Student{name='丽丽'}

    这这个栗子首先创建一个ThreadLocal,并重新了initialValue方法,如果不重写此方法,上来就get会报错,等于给它初始化。在主线程去set一个Student对象,然后开启2个子线程,一个线程去直接从ThreadLocal取数据,一个线程先设置另一个Student对象再去取数据,最后在主线程打印取出的数据。

    结果证明在一个线程存储数据只能在当前线程有效,并不影响其他线程的数据。

    源码分析

    ThreadLocal<T>存储的是数据,创建的时候需要为其指定泛型,最核心的方法应该就是set和get了,set是往当前线程保存数据,get是从当前线程获取数据。

    T 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 是一个内部类,内部有一个数组,数组里面存储的是Entry,该类继承自弱引用,
        //内部是以键值对形式存储数据,键就是ThreadlLocal,值就是要存储的对象,每个线程都定义有这么一个对象
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        //取出当前线程保存的数据返回,否则就创建初始值
        //setInitialValue()内部调用initialValue() ,这里看出我们为什么要在创建时候重写initialValue()方法了,不重写默认返回null
    
        return setInitialValue();
    }
    

    ThreadLocalMap getMap(Thread t) ——获取该线程的ThreadLocalMap 对象

    /**
     * Get the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param  t the current thread
     * @return the map
     */
    //每个线程都持有这么一个对象
    ThreadLocalMap getMap(Thread t) {
            return t.threadLocals;
     }
    

    void set(T value) ——为该线程存储数据

    /**
     * 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);
    }
    //获取当前线程的ThreadLocalMap,把数据对象存到这个数据结构中
    

    void remove()——移除当前线程ThreadLocal存储的数据

    /**
     * Removes the current thread's value for this thread-local
     * variable.  If this thread-local variable is subsequently
     * {@linkplain #get read} by the current thread, its value will be
     * reinitialized by invoking its {@link #initialValue} method,
     * unless its value is {@linkplain #set set} by the current thread
     * in the interim.  This may result in multiple invocations of the
     * {@code initialValue} method in the current thread.
     *
     * @since 1.5
     */
    //获取当前线程的ThreadLocalMap,把数据对象从改线程移除掉
     public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }
    

    通过源码分析可以看出,其实ThreadLocal在每个线程的数据操作,都是在操作每个线程的ThreadLocalMap ,每个线程都有一个ThreadLocalMap ,每个ThreadLocalMap 都有一个table数组存储着数据,set和get操作其实就是在这个table数组进行数据的操作(table数组存储的对象是Entry虚引用以键值对存储数据,键——ThreadLocalMap 自身,值——存储的对象),所以ThreadLocal可以在多个线程中互不干扰的操作自己的数据。

    相关文章

      网友评论

        本文标题:Android笔记——ThreadLocal原理浅析

        本文链接:https://www.haomeiwen.com/subject/hoxghxtx.html