咱们都知道在多线程的环境下,多个线程访问同一个共享变量会有并发问题,解决方式之一就是每个线程使用自己的本地变量,这个本地变量就是 ThreadLocal 实现的。
比如下面的代码:
private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();
public static void main(String[] args) throws Throwable {
Thread threadOne = new Thread(() -> {
Thread.currentThread().setName("threadOne");
threadLocal.set("ThreadOne:" + Thread.currentThread().getName());
System.out.println("线程 One set 后本地变量值为:" + threadLocal.get());
threadLocal.remove();
System.out.println("线程 One remove 后本地变量值为:" + threadLocal.get());
});
Thread threadTwo = new Thread(() -> {
Thread.currentThread().setName("threadTwo");
threadLocal.set(