ThreadLocal的基本用法

 

ThreadLocal的基本用法

关于threadLocal 类的解释是

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).

大概的意思关于threadLocal 类的解释是

 

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).

大概的意思是 每个线程都具有获取获取独立变量的能力,之间互不影响

我们可以通过threadLocal 的get 和set方法进行设置线程的值和获取线程的值

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

    /**
     * Variant of set() to establish initialValue. Used instead
     * of set() in case user has overridden the set() method.
     *
     * @return the initial value
     */
    private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

从上面的set和get方法可以看出 其内部维护了一个  ThreadLocalMap的 类 可以简单认为相当于一个HashMap  key是当前的线程类,value 是设置的值,这样就可以保证每个线程设置的值的独立性,不会被其他线程修改。

下来我们看一个简单的例子

package com.xiangxue.MyTest;

import java.util.concurrent.CountDownLatch;

/**
 * threadLocal的作用:线程变量。可以理解为是个map,类型 Map<Thread,Integer>
 */
public class ThreadLocalTest {

    public  static  void main(String[] args){
        CountDownLatch countDownLatch = new CountDownLatch(10);
        ThreadLocal<Long> threadLocal = new ThreadLocal();
        threadLocal.set(100L);
        for (int i=0;i<10;i++){
            ThreadLocalTest.threadLocalThread testThread = new ThreadLocalTest.threadLocalThread(threadLocal,countDownLatch);
            Thread thread = new Thread(testThread);
            thread.start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("主线程ThreadLocal的值是:"+threadLocal.get());
    }

    private  static  class  threadLocalThread implements  Runnable{
        ThreadLocal<Long> threadLocal = new ThreadLocal();
        CountDownLatch countDownLatch = null;

        public threadLocalThread(ThreadLocal<Long> threadLocal, CountDownLatch countDownLatch) {
            this.threadLocal = threadLocal;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {

            threadLocal.set(countDownLatch.getCount());

            System.out.println("当前ThreadLocal的值是:"+threadLocal.get());
            countDownLatch.countDown();
        }
    }
}

 运行的结果:

当前ThreadLocal的值是:10
当前ThreadLocal的值是:9
当前ThreadLocal的值是:8
当前ThreadLocal的值是:10
当前ThreadLocal的值是:6
当前ThreadLocal的值是:5
当前ThreadLocal的值是:4
当前ThreadLocal的值是:3
当前ThreadLocal的值是:2
当前ThreadLocal的值是:1
主线程ThreadLocal的值是:101111111111

 

上一篇:深入剖析线程同步工具CountDownLatch原理


下一篇:Java并发编程实践:使用原子锁和CountDownLatch模拟并发请求