java并发--ThreadLocal

本文讲解ThreadLocal在Java中的应用,涉及线程隔离机制、ThreadLocalMap和实例使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、作用

用于线程隔离一个变量

二、原理

1、线程thread有一个ThreadLocal.ThreadLocalMap类型的属性threadLocals

2、ThreadLocalMap维护着一个数组,数组的元素是Entry对象,Entry中有key、value,key为ThreadLocal对象,value是要线程隔离的值

3、这个数组处理hash冲突的方式是开放寻址法,即向后遍历空位置存放

4、entry的key是弱引用类型,如果没有其他引用,在GC时会被清理,就会产生一个key为null,value不为null的entry,可以通过remove()清理这些entry;

      使用ThreadLocal.get()方法后,key变成了强引用,就不会被GC为null了

三、使用

在线程thread中定义一个threadLocal对象,作为entry的key;value可以通过initialValue()、set()、get()方法操作

四、例子

public class ThreadLocalTest implements Runnable{
    
    ThreadLocal<Student> studentThreadLocal = new ThreadLocal<Student>();

    @Override
    public void run() {
        String currentThreadName = Thread.currentThread().getName();
        System.out.println(currentThreadName + " is running...");
        Random random = new Random();
        int age = random.nextInt(100);
        System.out.println(currentThreadName + " is set age: "  + age);
        Student Student = getStudentt(); //通过这个方法,为每个线程都独立的new一个Studentt对象,每个线程的的Studentt对象都可以设置不同的值
        Student.setAge(age);
        System.out.println(currentThreadName + " is first get age: " + Student.getAge());
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println( currentThreadName + " is second get age: " + Student.getAge());
        
    }
    
    private Student getStudentt() {
        Student Student = studentThreadLocal.get();
        if (null == Student) {
            Student = new Student();
            studentThreadLocal.set(Student);
        }
        return Student;
    }

    public static void main(String[] args) {
        ThreadLocalTest t = new ThreadLocalTest();
        Thread t1 = new Thread(t,"Thread A");
        Thread t2 = new Thread(t,"Thread B");
        t1.start();
        t2.start();
    }
    
}

class Student{
    int age;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值