public class ThreadLocalDemo {
static {
threadLocal = new ThreadLocal<>();
}
public static ThreadLocal<String> threadLocal;
public synchronized static void main(String[] args) throws InterruptedException {
new Thread(() -> {
threadLocal.set("A线程变量");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadLocal.remove();
System.out.println(Thread.currentThread().getName()+threadLocal.get());
},"A线程").start();
new Thread(() -> {
threadLocal.set("B线程变量");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+threadLocal.get());
},"B线程").start();
//底层其实是一个map,k为当前线程threadLocal对象,v为对应的值
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
//public void set(T value) {
// Thread t = Thread.currentThread();
// ThreadLocal.ThreadLocalMap map = getMap(t);
// if (map != null)
// map.set(this, value);
// else
// createMap(t, value);
//}
/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
//ThreadLocal.ThreadLocalMap getMap(Thread t) {
// return t.threadLocals;
//}
/**
* Create the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the map
*/
//void createMap(Thread t, T firstValue) {
// t.threadLocals = new ThreadLocal.ThreadLocalMap(this, firstValue);
//}
}
}