一、作用
用于线程隔离一个变量
二、原理
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;
}
}