一、什么是ThreadLocal
0.public class ThreadLocal extends Object {…}
1.每一个线程都可以通过ThreadLocal对象的get或者set方法来获取或者设置该线程独有的,自己的变量副本。
2.各个线程中的该变量副本都是独立的,其他线程访问不到。
3.该局部变量存储每一个线程和对应的数值。可以从源码中知道:
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
二、特点
1.该ThreadLocal变量是局部的线程变量。
2.该线程变量是private私有和static静态的。
三、常见API
1.get():获取当前线程拷贝的局部线程变量的值。
2.initialValue():设置当前线程赋予局部线程变量的初始值。
3.remove():移除当前线程的局部变量的值
4.set(T value):为当前线程拷贝的局部变量设定一个指定的值。
四、代码示例
public class Profiler {
/*
* 线程变量
* */
private static final ThreadLocal TIME_THREADLOCAL = new ThreadLocal() {
@Override
protected Long initialValue() {
return System.currentTimeMillis();
}
};
public static final void begin() {
TIME_THREADLOCAL.set(System.currentTimeMillis());
}
public static final long end() {
return System.currentTimeMillis() - TIME_THREADLOCAL.get();
}
public static long get(){
return TIME_THREADLOCAL.get();
}
public static void main(String[] args) throws InterruptedException {
Profiler.begin();
TimeUnit.SECONDS.sleep(1);
System.out.println("Cost: " + Profiler.end() + " mills.");
new Thread(new Runnable() {
@Override
public void run() {
Profiler.begin();
System.out.println(Profiler.get());
System.out.println(Profiler.TIME_THREADLOCAL);
}
}).start();
new Thread(){
@Override
public void run() {
Profiler.begin();
System.out.println(Profiler.get());
System.out.println(Profiler.TIME_THREADLOCAL);
}
}.start();
}
}