ThreadLocal能够保存线程独有的一份变量,这样就不用通过参数传递,直接在线程执行的过程中随时随地get出来
此处没有例子,只是说明一下源码到底是怎么去存的
1、使用的时候,只需要创建ThreadLocal对象,重写initialValue方法,初始化我们需要存储的值,默认值为null,因为没有通过initialValue初始化
private ThreadLocal<Integer> num=new ThreadLocal<Integer>(){
public Integer initialValue(){
return 0;
}
};
2、在initialValue是怎么存放在线程中的呢?
通过ThreadLocal源码并结合Thread可以清晰的看出,Thread中有一个缓存属性,配合ThreadLocal使用的,所有new出来的ThreadLocal都会被每个线程保存在 threadLocals 中。
实际上每个线程都是Thread的一个对象,所以我们在使用的时候,只是在操作这个线程对象的变量而已
public class Thread implements Runnable {
...
ThreadLocal.ThreadLocalMap threadLocals = null