From 0f075415a8276c00f69aaa7d601934e6d97c7d39 Mon Sep 17 00:00:00 2001 From: Omooo <869759698@qq.com> Date: Mon, 30 Mar 2020 20:39:09 +0800 Subject: [PATCH] =?UTF-8?q?Create=20=E8=AF=B4=E8=AF=B4=20ThreadLocal=20?= =?UTF-8?q?=E7=9A=84=E5=8E=9F=E7=90=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../技巧心得相关/说说 ThreadLocal 的原理.md | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 blogs/Android/Framework/Interview/技巧心得相关/说说 ThreadLocal 的原理.md diff --git a/blogs/Android/Framework/Interview/技巧心得相关/说说 ThreadLocal 的原理.md b/blogs/Android/Framework/Interview/技巧心得相关/说说 ThreadLocal 的原理.md new file mode 100644 index 0000000..e0244a2 --- /dev/null +++ b/blogs/Android/Framework/Interview/技巧心得相关/说说 ThreadLocal 的原理.md @@ -0,0 +1,73 @@ +--- +说说 ThreadLocal 的原理 +--- + +1. ThreadLocal 的适用于什么场景? +2. ThreadLocal 的使用方式是怎样的? +3. ThreadLocal 的实现原理怎样的? + +```java +private static void prepare(boolean quitAllowed){ + sThreadLocal.set(new Looper(quitAllowed)); +} +static final ThreadLocal sThreadLocal = new ThreadLocal(); +public static Looper myLooper(){ + return sThreadLocal.get(); +} +``` + +```java +private static final ThreadLocal sThreadInstance = new ThreadLocal(){ + @Override + protected Choreographer initialValue(){ + Looper looper = Looper.myLooper(); + return new Choreographer(looper); + } +} +public static Choreographer myLooper(){ + return sThreadLocal.get(); +} +``` + +```java +public T get(){ + Thread currentThread = Thread.currentThread(); + Values values = values(currentThread); + if(values!=null){ + Object[] table = values.table; + int index = hash & values.mask; + if(this.reference == table[index]){ + return (T)table[index + 1]; + }else{ + values = initializeValues(currentThread); + } + } + return (T)values.getAfterMiss(this); +} +Object getAfterMiss(ThreadLocal key){ + Object[] table = this.table; + int index = key.hash & mask; + Object value = key.initialVaule(); + table[index] = key.reference; + table[index + 1] = value; + size++; + cleanUp(); + return value; +} + +public void set(T value){ + Thread currentThread = Thread.currentThread(); + Values values = values(currentThread); + if(values == null){ + values = initalizeValues(currentThread); + } + values.put(this, value); +} +``` + +#### 总结 + +1. 同一个 ThreadLocal 对象,在不同线程 get 返回不同的 value +2. Thread 对象里有张表,保存 ThreadLocal 到 value 的映射关系 +3. 这张表是怎么实现的? +4. 是如何解决 hash 冲突的? \ No newline at end of file