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 的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的值是:7
当前ThreadLocal的值是:7
当前ThreadLocal的值是:5
当前ThreadLocal的值是:5
当前ThreadLocal的值是:3
当前ThreadLocal的值是:2
当前ThreadLocal的值是:1
主线程ThreadLocal的值是:100

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值