参考URL:Java并发性和多线程介绍
1.初始化
初始化ThreadLocal对所有线程可见,set()方法设置的值只对当前线程可见。
private ThreadLocal myThreadLocal = new ThreadLocal<String>() {
// 新建时覆写它的initialValue()方法,实现线程变量初始化,对所有线程都可见
@Override protected String initialValue() {
return "This is the initial value";
}
};
2.一个完整的ThreadLocal示例
public class ThreadLocalExample {
public static class MyRunnable implements Runnable {
private ThreadLocal<Integer> threadLocal =
new ThreadLocal<Integer>();
@Override
public void run() {
threadLocal.set( (int) (Math.random() * 100D) );
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println(threadLocal.get());
}
}
public static void main(String[] args) {
MyRunnable sharedRunnableInstance = new MyRunnable();
/*
* 两个线程使用相同的runable实例,
* 但是由于是ThreadLocal对象,所以两个线程无法看到彼此的值,
* 它们可以设置或者获取不同的值。
*/
Thread thread1 = new Thread(sharedRunnableInstance);
Thread thread2 = new Thread(sharedRunnableInstance);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
}
3.InheritableThreadLocal
ThreadLocal实例内部每个线程只能看到自己的私有值,InheritableThreadLocal允许一个线程创建的所有子线程访问其父线程的值,InheritableThreadLocal是ThreadLocal的一个子类。