ThreadLocal
ThreadLocal用于保存线程线程本地变量,访问这个变量的每个线程都会有这个变量的一个本地副本,多个线程同时对这个变量进行读写操时,实际上操作的是线程自己本地内存中的变量,从而避免了线程安全的问题。
比如多个方法都用到某个参数,为了避免一直传递,可以放到ThreadLocal中。
// threadLocal :主线程的threadLocal不会往子线程复制的,只是保留了一个空副本
public static final ThreadLocal<Map<String,Object>> threadLocal = new ThreadLocal<>();
static {
Map<String, Object> map = new ConcurrentHashMap<>();
map.put("cnt",0);
threadLocal.set(map);
}
public static void main(String[] args) {
System.out.println(threadLocal.get().get("cnt"));
CountDownLatch countDownLatch = new CountDownLatch(9);
for (int i = 1;i<10;i++){
int finalI = i;
try {
new Thread(new Runnable() {
public void run() {
//threadLocal 线程隔离这里会报空指针异常,所以一般我们都会做一个get方法,如果是空则付一下默认值
System.out.println(threadLocal.get().get("cnt"));
}
}).start();
}catch (Exception e) {
throw new RuntimeException("111");
} finally {
countDownLatch.countDown();
}
}
try {
countDownLatch.await(); //保证之前的所有的线程都执行完成,才会走下面的;
} catch (Exception e) {
throw new RuntimeException();
}
}
InheritableThreadLocal
能够使让子线程访问到父线程中设置的本地变量的值
// InheritableThreadLocal 可以向子线程传递,这个复制是引用复制,即子线程的修改会反馈到主线程
public static final InheritableThreadLocal<Map<String,Object>> threadLocal = new InheritableThreadLocal<>();
static {
Map<String, Object> map = new ConcurrentHashMap<>();
map.put("cnt",0);
threadLocal.set(map);
}
public static void main(String[] args) throws InterruptedException {
System.out.println("最初:"+threadLocal.get().get("cnt"));
CountDownLatch countDownLatch = new CountDownLatch(9);
for (int i = 1;i<10;i++){
int finalI = i;
if (i==7){
Thread.sleep(i*100);
}
new Thread(new Runnable() {
public void run() {
try {
Map<String, Object> subMap = threadLocal.get();
System.out.println(Thread.currentThread().getName()+"加之前:"+threadLocal.get().get("cnt"));
subMap.put("cnt",Integer.parseInt(subMap.get("cnt").toString())+finalI);
threadLocal.set(subMap);
System.out.println(Thread.currentThread().getName()+"加之后:"+threadLocal.get().get("cnt"));
}catch (Exception e) {
throw new RuntimeException("111");
} finally {
countDownLatch.countDown();
}
}
}).start();
}
try {
countDownLatch.await(); //保证之前的所有的线程都执行完成,才会走下面的;
} catch (Exception e) {
throw new RuntimeException();
}
System.out.println("最终:"+threadLocal.get().get("cnt"));
}
InheritableThreadLocal可以保证子线程获得主线程的变量,其实是在线程创建的时候从主线程中对线程变量做了一个地址引用,所以说在子线程结束之后,主线程的线程变量也改变了。
这里需要考虑下,如果使用得当线程池,核心线程创建之后是不会销毁的,所以此变量就一直保留了下来。
阿里的transmittablethreadlocal 可以解决InheritableThreadLocal 和线程池搭配,核心线程不销毁,导致的InheritableThreadLocal 错乱问题。
TransmittableThreadLocal详解_邋遢的流浪剑客的博客-CSDN博客_transmittable-thread-local这个老哥写的挺详细的。