栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

ThreadLocal使用以及实现原理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ThreadLocal使用以及实现原理

        ThreadLocal用于实现线程内部的数据共享,对于同一个线程来说,使用ThreadLocal获取的存储对象是同一个;不同的线程使用ThreadLocal会从不同的内存区域中获取存储对象,也就是ThreadLocal会针对当前线程开辟一块独立的存储空间。ThreadLocal存储Integer如下:

public class ThreadLocalTest  {
    
    public ThreadLocal threadLocal = new ThreadLocal();
    public void test {
        
        for(int i=0; i<2;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Integer value = new Integer();
                    threadLocal.set(value);
                    threadLocal.get();
                    //操作
                    try {
                        Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                    }
                    threadLocal.remove();
                   
                }
            }).start();
        }
    }
   
}

创建ThreadLocal对象:

//注意泛型
public class ThreadLocal {
    
    
    public ThreadLocal() {

    }
}

ThreadLocal存储的对象是泛型化对象,在构造ThreadLocal对象时指定存储的对象的具体类型:

ThreadLocal tl = new ThreadLocal()

ThreadLocal存储对象 - set方法

    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 getMap(Thread t) {
        return t.threadLocals;
    }
    
    //很关键,此处传入this,thread和ThreadLocalMap一一对象,多个ThreadLocalMap绑定同一个ThreadLocal
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

    
    static class ThreadLocalMap {

        
        static class Entry extends WeakReference> {
            
            Object value;

            Entry(ThreadLocal k, Object v) {
                super(k);
                value = v;
            }
        }

        
        private static final int INITIAL_CAPACITY = 16;

        
        private Entry[] table;

        
        private int size = 0;

        
        private int threshold; // Default to 0

      
        ThreadLocalMap(ThreadLocal firstKey, Object firstValue) {
            table = new Entry[INITIAL_CAPACITY];
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }
    }






Thread中的threadLocals对象:

public class Thread implements Runnable {
    
    
    //每个Thread中都有一个ThreadLocalMap,ThreadLocalMap中存储了ThreadLocal和需要存储的对象
    ThreadLocal.ThreadLocalMap threadLocals = null;

}

        由set(T value)源码可见,每个Thread中都有一个ThreadLocalMap,而ThreadLocalMap绑定了ThreadLocal和需要存储的对象,也就是同一个ThreadLocal对象为不同的线程各自开辟了一块存储空间,每个线程只访问自己存储空间中的对象。

ThreadLocal读取对象 - get

   public T get() {
        Thread t = Thread.currentThread();
        //从当前线程中获取ThreadLocalMap
        ThreadLocalMap map = getMap(t);
        //从ThreadLocalMap中获取存储的值
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }


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

get方法会从当前线程中获取ThreadLocalMap对象,而ThreadLocalMap中存储了数据值。

ThreadLocal删除对象-remove

public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
}

从当前线程中获取ThreadLocalMap对象,从ThreadLocalMap中删除。

Android中每个线程中只能有一个looper对象,就是靠ThreadLocal来实现的:

public final class Looper {
    
    private static final String TAG = "Looper";

    // sThreadLocal.get() will return null unless you've called prepare().
    @UnsupportedAppUsage
    //用于为不同的线程保存不同的looper对象
    static final ThreadLocal sThreadLocal = new ThreadLocal();
    

    
    public static void prepare() {
        prepare(true);
    }

    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));
    }


    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

1、sThreadLocal对象

sThreadLocal用static final修饰,所以Android中的所有的Looper对象都是靠sThreadLocal这个对象存储。

2、prepare方法

sThreadLocal.get()用于获取当前线程中的Looper对象,如果已经存在的话,抛出运行时异常。如果当前线程中不存在Looper对象,创建Looper对象,并用sThreadLocal存储。

3、myLooper()方法

用于获取当前线程中的Looper对象,通过sThreadLocal获取当前线程中的ThreadLocalMap中存储的Looper对象。

4、创建MessageQueue

在Looper的构造方法中创建MessageQueue对象,因为对于每一个线程来说,Looper的构造方法只能执行一次,因此一个线程只能有一个Looper对象、一个Looper对象只能有一个MessageQueue对象。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/877081.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号