参考文档:

https://blog.csdn.net/u012834750/article/details/71646700

threadlocal内存泄漏:http://www.importnew.com/22039.html

什么是ThreadLocal

  首先明确一个概念,那就是ThreadLocal并不是用来并发控制访问一个共同对象,而是为了给每个线程分配一个只属于该线程的变量,顾名思义它是local variable(线程局部变量)。它的功用非常简单,就是为每一个使用该变量的线程都提供一个变量值的副本,是每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突,实现线程间的数据隔离。从线程的角度看,就好像每一个线程都完全拥有该变量

应用场景:

数据库连接池,session

一个简单栗子

public class ThreadLocalTest implements Runnable {
    static ThreadLocal<String> tl = new ThreadLocal<String>();

    public static void main(String[] args) {
        for(int i=0;i<10;i++){
            Thread t = new Thread(new ThreadLocalTest(), "t"+i);
            t.start();
        }
    }

    @Override
    public void run() {
        tl.set(Thread.currentThread().getName());
        System.out.println(Thread.currentThread().getName()+" == tname :"+tl.get());
    }
}
View Code

相关文章:

  • 2021-08-04
  • 2021-07-11
  • 2021-10-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-23
猜你喜欢
  • 2021-04-10
  • 2021-07-18
  • 2021-10-06
  • 2021-05-15
  • 2021-10-31
  • 2021-08-02
相关资源
相似解决方案