Java 中的ThreadLocal

What is ThreadLocal ?

1.ThreadLocal 是一个创建线程局部变量的类

2.通常情况下 ,一个对象中创建的变量是可以被任何一个线程访问的,也就是共享变量,ThreadLocal 创建的变量只能被当前线程访问,其他线程无法访问和修改

Why is ThreadLocal ?


1.ThreadLocal  是为了解决多线程资源共享访问的问题,为了让每个线程中有自己本地独立的实例且需要被多个方法调用,该变量在线程之间隔离,但是在方法和类之间可以共享

常用场景
1.JDBC中管理connection,借助ThreadLocal ,当前线程操作的都是线程池中的同一个connection,保证了数据库事物的正确性
2.避免常用的一些参数的传递,常用的信息Session,Cookie等维护到ThreadLocal 中,该线程中的方法都能访问,而不需要参数传递

内部实现
ThreadLocal将变量的各个副本值保存在各个线程Thread对象实例里面。而Thread对象实例是通过ThreadLocalMap数据结构来存储副本值,ThreadLocalMap中存储的是ThreadLocalMap.Entry,Entry实例是对ThreadLocal某个实例的弱引用

package com.app.demo.thread.threadlocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Run
{

    private static ThreadLocal<String> local = new ThreadLocal<>();
    
    public static void main(String[] args)
    {
        local.set("This is a threadlocal test ");

        Thread oThread = new Thread(new Runnable()
        {
            public void run()
            {
                System.out.println(Thread.currentThread().getName());
                System.out.println(local.get());
            }
        });

        ExecutorService executor = Executors.newFixedThreadPool(5);
        
        for (int i = 0; i < 10; i++)
        {
            executor.submit(oThread);
        }
       
        System.out.println("<--->"+Thread.currentThread().getName());
        
        System.out.println("<--->"+local.get());
        
        print();
    }

    public static void  print()
    {
        System.out.println("<-++-++->"+local.get());
    }
    
}
pool-1-thread-1
pool-1-thread-3
null
pool-1-thread-2
pool-1-thread-4
null
null
null
pool-1-thread-5
null
pool-1-thread-2
null
pool-1-thread-3
pool-1-thread-1
null
pool-1-thread-5
null
pool-1-thread-4
null
null
<--->main
<--->This is a threadlocal test 
<-++-++->This is a threadlocal test 

ThreadLocal 的参考文章

https://ylgrgyq.github.io/2017/09/21/java-threadlocal/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值