ThreadLocal API

如果不赋初始值那么返回null
public class Basic {
//ThreadLocal<T>
static ThreadLocal<Long> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
System.out.println("threadLocal = " + threadLocal.get());//null
}
}
public class Basic {
// ThreadLocal<T>
static ThreadLocal<Long> threadLocal =
new ThreadLocal<Long>() {
/**
* 返回此线程局部变量的当前线程的“初始值”。该方法将在线程第一次使用get方法访问变量时调用,
* 除非该线程之前调用了set方法,在这种情况下,不会为该线程调用initialValue方法。
* 通常,每个线程最多调用一次此方法,但如果后续调用remove后跟get,
* 则可能会再次调用它。 此实现仅返回null ;
* 如果程序员希望线程局部变量具有除null以外的初始值,则必须将ThreadLocal子类化,并重写此方法。
* 通常,将使用匿名内部类。
*
* @return 此线程本地的初始值
*/
@Override
protected Long initialValue() {
Thread thread = Thread.currentThread();
String name = thread.getName();
System.out.println("threadName = " + name + ", ");
return thread.getId();
}
};
public static void main(String[] args) {
new Thread(){
/**
*如果该线程是使用单独的Runnable运行对象构造的,则调用该Runnable对象的run方法;
* 否则,此方法不执行任何操作并返回。
* Thread的子类应覆盖此方法
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
@Override
public void run() {
System.out.println("tow threadLocal = " + threadLocal.get());
threadLocal.set(122L);
System.out.println("tow threadLocal = " + threadLocal.get());
}
}.start();
System.out.println("one threadLocal = " + threadLocal.get());
threadLocal.set(233L);
//threadLocal.remove();//调remove()方法后在get() 会重新调initialValue()方法
System.out.println("one threadLocal = " + threadLocal.get());
}
}