Java中的ThreadLocal类可以让你创建的变量只被同一个线程进行读和写操作。
- 创建一个ThreadLocal对象
private ThreadLocal myThreadLocal = new ThreadLocal();
- 访问ThreadLocal对象
//get()方法会返回一个Object对象,而set()方法则依赖一个Object对象参数
myThreadLocal.set("A thread local value");
String threadLocalValue = (String) myThreadLocal.get();
- ThreadLocal泛型
private ThreadLocal myThreadLocal1 = new ThreadLocal<String>();
myThreadLocal1.set("Hello ThreadLocal");
String threadLocalValues = myThreadLocal.get();
- 初始化ThreadLocal
//在set()方法调用前,当调用get()方法的时候,所有线程都可以看到同一个初始化值
private ThreadLocal myThreadLocal = new ThreadLocal<String>() {
@Override protected String initialValue() {
return "This is the initial value";
}
};
5.例子
public class ThreadLocalTest {
private static ThreadLocal<Integer> x=new ThreadLocal<Integer>();
private static ThreadLocal<MyThreadScopeData> myThreadScopeData=new ThreadLocal<MyThreadScopeData>();
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
int data = new Random().nextInt() ;
System.out.println(Thread.currentThread().getName() + ":" + data);
x.set(data);
MyThreadScopeData.getInstance().setName("name "+data+" ");
MyThreadScopeData.getInstance().setAge(data);
new A().get();
new B().get();
}
}).start();
}
}
static class A{
public void get(){
int data=x.get();
System.out.println("A--"+Thread.currentThread().getName()+":"+data);
MyThreadScopeData myData=MyThreadScopeData.getInstance();
System.out.println("A--"+Thread.currentThread().getName()+" getData: "+myData.getName()+"age: "+myData.getAge());
}
}
static class B{
public void get(){
int data=x.get();
System.out.println("B--"+Thread.currentThread().getName()+":"+data);
MyThreadScopeData myData=MyThreadScopeData.getInstance();
System.out.println("B--"+Thread.currentThread().getName()+" getData:"+myData.getName()+"age:"+myData.getAge());
}
}
}
class MyThreadScopeData{
private MyThreadScopeData(){}
public static MyThreadScopeData getInstance(){ //饥汉模式
MyThreadScopeData instance=map.get();
if(instance==null){
instance=new MyThreadScopeData();
map.set(instance);
}
return instance;
}
//饱汉模式 private static MyThreadScopeData instance=new MyThreadScopeData();
//private static MyThreadScopeData instance=null;
private static ThreadLocal<MyThreadScopeData> map=new ThreadLocal<MyThreadScopeData>();
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
输出结果:
Thread-1:585994092
A--Thread-1:585994092
A--Thread-1 getData: name 585994092 age: 585994092
B--Thread-1:585994092
B--Thread-1 getData:name 585994092 age:585994092
Thread-0:-1879022169
A--Thread-0:-1879022169
A--Thread-0 getData: name -1879022169 age: -1879022169
B--Thread-0:-1879022169
B--Thread-0 getData:name -1879022169 age:-1879022169