ThreadLocal是线程隐式变量,每个线程都会有一份。
static ThreadLocal<String> locals = ThreadLocal.withInitial(() -> { System.out.println("初始化值"); return "java"; }); public static void main(String[] args) { //locals.set("ruby"); //locals.remove(); System.out.println("线程id:" + Thread.currentThread().getId() + ", 值:" + locals.get()); new Thread(() -> { //locals.set("c#"); System.out.println("线程id:" + Thread.currentThread().getId() + ", 值:" + locals.get()); }).start(); } // 输出 初始化值 线程id:1, 值:java 初始化值 线程id:12, 值:java
其中初始值,只有在执行get时才会被初始化,且没有调用过set。
static ThreadLocal<String> locals = ThreadLocal.withInitial(() -> { System.out.println("初始化值"); return "java"; }); public static void main(String[] args) { locals.set("ruby"); locals.remove(); System.out.println("线程id:" + Thread.currentThread().getId() + ", 值:" + locals.get()); new Thread(() -> { locals.set("c#"); System.out.println("线程id:" + Thread.currentThread().getId() + ", 值:" + locals.get()); }).start(); } // 输出 初始化值 线程id:1, 值:java 线程id:12, 值:c#
可以看到remove后,才会初始化值。