ThreadLocal的详解

了解知识点:

强引用:创建对象的引用

软引用:应用场景在缓存

弱引用:应用场景在事务

虚引用:应用场景在直接内存管理

ThreadLocal是线程隔离的,每个线程间互不干扰

import java.util.concurrent.TimeUnit;

public class hacker_01_ThreadLocalDemo {


    public static ThreadLocal<User> th=new ThreadLocal<>();


    public static void main(String[] args) throws InterruptedException {

        // 第一个线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                User user = new User();
                user.setName("小凯");
                user.setAge(1);
                // set user data
                th.set(user);
                // get user data
                User getUser=th.get();
                System.out.println("第一个线程:"+getUser);

            }
        }).start();

        // wait second thread run
        TimeUnit.MILLISECONDS.sleep(1000);

        // 第二个线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                // get user data
                User user=th.get();
                System.out.println("第二个线程:"+user);
            }
        }).start();

    }





}

结果

从结果图可以发现,ThreadLocal具有天生线程隔离机制,保证本线程的东西只能本线程能够访问使用。

导致ThreadLocal线程隔离的原因是什么?

ThreadLocal的set源码

获取一个ThreadLocalMap,存放的键为ThreadLocal的对象,值为要保存的value。

ThreadLocal的getMap源码

 

threadLocals为Thread的成员变量,保证了不同线程的threadLocals是不相同。

当threadLocals为null时,调用createMap方法

 

 上图可见,map中存放的是Entry对象,Entry对象中的键为弱引用类型,值是强引用类型。

弱引用的类型,若内存中ThreadLocal的对象为空时,弱引用就会指向null,方便jvm的gc对ThreadLoca对象回收,防止内存泄露。

猜你喜欢

转载自blog.csdn.net/Growing_hacker/article/details/108866301