ThreadLocal有哪些应用场景?底层如何实现?

1.如何使用?

public class ThreadLocalExample {
    private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        Runnable task = () -> {
            threadLocal.set("Hello from thread " + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String value = threadLocal.get();
            System.out.println(value);
            threadLocal.remove();
        };

        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);

        thread1.start();
        thread2.start();
    }
}

2.如何理解?

每个thread线程上有一个threadlocalmap变量,用来存储当前线程的threadlocal数据。

当调用threadlocal的set或get方法时,本质上是操作本线程的threadlocalmap。key用来存储当前threadlocal,value用来存储值。

实际上,threadlocal只是用来操作当前thread线程threadlocalmap的工具类而已,threadlocalmap并不是存储在threadlocal中。

 3.注意哪些问题?

1.内存泄露/溢出:需要手动调用threadlocal.remove()来销毁

4.应用场景有哪些? 

1.多个场景需要用到同一种变量,但每个场景里所用到的变量值不同,需要相互隔离的。

2.隔离线程,存储一些不安全的工具对象。

3.spring中的事物。

4.springMVC中的httpsession,httpservletrequest,httpservletresponse

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Deryck_德瑞克

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值