2.3 ThreadLocal
2.3.1 概念
ThreadLocal类并不是用来解决多线程环境下的共享变量问题,而是用来提供线程内部的独享变量。在多线程环境下,可以保证各个线程之间的变量互相隔离、相互独立。
2.3.2 使用
ThreadLocal实例一般定义为private static类型的,在一个线程内,该变量共享一份,类似上下文作用,可以用来上下传递信息。
public class App {
private static ThreadLocal<App> threadLocal = new ThreadLocal<>();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
threadLocal.set(new App());
App app = threadLocal.get();
System.out.println(Thread.currentThread().getName()+"---"+app);
},"t1");
Thread t2 = new Thread(() -> {
App app = threadLocal.get();
System.out.println(Thread.currentThread().getName()+"---"+app);
},"t2");
t1.