ThreadLocal
仿ThreadLocal源碼理解其原理;
1.定義自己的ThreadLocal實現
import java.util.HashMap; public class MyThreadLocal<T> { public class MyThreadLocalMap { private HashMap<String, T> map; private MyThreadLocalMap() { map = new HashMap<String, T>(); } } public T initValue() { return null; } public void createMap(MyThread t) { t.setLocalMap(new MyThreadLocalMap()); } public T setInitValue(MyThread t) { T value = initValue(); MyThreadLocalMap map = t.getLocalMap(); if (null == map) { createMap(t); } t.getLocalMap().map.put(String.valueOf(this.hashCode()), value); return value; } public void set(T value) { MyThread thread = (MyThread)Thread.currentThread(); MyThreadLocalMap localMap = thread.getLocalMap(); if (null == localMap) { createMap(thread); } thread.getLocalMap().map.put(String.valueOf(this.hashCode()), value); } public T get() { MyThread thread = (MyThread)Thread.currentThread(); MyThreadLocalMap localMap = thread.getLocalMap(); if (null != localMap) { return localMap.map.get(String.valueOf(this.hashCode())); } return setInitValue(thread); } public void remove() { MyThread thread = (MyThread)Thread.currentThread(); MyThreadLocalMap localMap = thread.getLocalMap(); if (null != localMap) { localMap.map.remove(String.valueOf(this.hashCode())); } } }
2.繼承Thread實現自己的Thread
public class MyThread extends Thread { private MyThreadLocal.MyThreadLocalMap localMap; public MyThread(Runnable runnable) { super(runnable); } public void setLocalMap(MyThreadLocal.MyThreadLocalMap map) { localMap = map; } public MyThreadLocal.MyThreadLocalMap getLocalMap() { return localMap; } }
測試代碼:
public class Main { public static void main(String[] args) { Runnable runnable = new Runnable() { public void run() { MyThreadLocal local = new MyThreadLocal() { @Override public Object initValue() { return Thread.currentThread().getName(); } }; System.out.println(local.get()); } }; MyThread thread1 = new MyThread(runnable); MyThread thread2 = new MyThread(runnable); thread1.setName("thread1"); thread2.setName("thread2"); thread2.start(); thread1.start(); } }
概述
ThreadLocal即線程變量(自己這麼叫的不是很準確),極大的方便線程獨享資源的管理,不需要再對資源進行管理避免了因多線程造成的問題;ThreadLocal將線程自己的數據封裝到內部,用ThreadLocal計算出hashcode爲鍵值(本文用的HashMap存儲,講明原理),通過內部類Entity實現存儲(哈希數組初始值16);