/** * 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. */ publicvoidset(T value) { Threadt= Thread.currentThread(); ThreadLocalMapmap= getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }
/** * 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() { Threadt= Thread.currentThread(); ThreadLocalMapmap= getMap(t); if (map != null) { ThreadLocalMap.Entrye= map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") Tresult= (T)e.value; return result; } } return setInitialValue(); }
值的修改都是在自己线程中操作的,所以是线程安全的。
使用场景
每个线程需要有自己单独的实例
实例需要在多个方法中共享,但不希望被多线程共享
Android中Hander
1 2 3 4 5 6 7
staticfinal ThreadLocal<Looper> sThreadLocal = newThreadLocal<Looper>(); privatestaticvoidprepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { thrownewRuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(newLooper(quitAllowed)); }