public class ThreadLocalDemo { static ThreadLocal threadLocal = new ThreadLocal();
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
threadLocal.set("1111");
System.out.println(threadLocal.get());
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(threadLocal.get());
threadLocal.set("2222");
System.out.println(threadLocal.get());
}
}).start();
}
}
结果 1111 null 2222
实现线程之间隔离,通过map来实现,k为threadlocal v为需要存储的对象 注意内存泄漏,调用线程的remove方法,hashmap的本质就是对key通过算法映射成数组的下表。
threadlocal thread threadlocalMap之间的关系
threadlocalmap是threadlocl的一个静态内部类,thread也持有threadllocalmap的一个引用