关于ThreadLocal

1.ThreadLocal 的父类为Object

2.用于保存某个线程共享变量

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the {@code ThreadLocal} instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

3.每个线程底层维护了一个map,key为threadlocal对象,value为threadLocal变量的值。

ThreadLocalMap is a customized hash map suitable only for maintaining thread local values. No operations are exported outside of the ThreadLocal class. The class is package private to allow declaration of fields in class Thread. To help deal with very large and long-lived usages, the hash table entries use WeakReferences for keys. However, since reference queues are not used, stale entries are guaranteed to be removed only when the table starts running out of space.
4.set方法

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

5.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 map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

6.remove方法

 /**
     * 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
     */
     public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }

7.简单使用示例

import java.util.Random;

/**
 * Created by zfr on 2018/08/05.
 *ThreadLocal 的例子
 */
public class ThreadLocalTest {
    static ThreadLocal threadLocal = new ThreadLocal<>();
    public static void main(String[] args) {
            // TODO Auto-generated method stub
        for(int i = 0;i<2;i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int data = new Random().nextInt(100);
                    System.out.println(Thread.currentThread().getName()+"创建了数据:"+data);
                    threadLocal.set(data);
                    TestGet.get();
                }
            }).start();
        }
        ThreadLocalTest a = new  ThreadLocalTest();
        System.out.println();
    }
    static  class  TestGet{
        public static void  get(){
            System.out.println(Thread.currentThread().getName()+"--"+threadLocal.get());
        }
    }
}

输出:

Thread-0创建了数据:22
Thread-1创建了数据:76
Thread-0–22
Thread-1–76

你可能感兴趣的:(学习记录)