System.out.println("A form "+Thread.currentThread().getName()+
" " + mtl.getAge()+" "+mtl.getName());
}
}
static class B{
public void get()
{
MyThreadLocal mtl = MyThreadLocal.getInstance();
System.out.println("B from "+Thread.currentThread().getName()+
" " + mtl.getAge()+" "+mtl.getName());
}
}
}
class MyThreadLocal{
private String name;
private int age;
private static ThreadLocal<MyThreadLocal> tl = new ThreadLocal<MyThreadLocal>();
private static MyThreadLocal instance =null;
private MyThreadLocal(){}
public static MyThreadLocal getInstance()
{
instance = tl.get();
if(instance == null)
{
instance = new MyThreadLocal();
tl.set(instance);
}
return instance;
}
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-0 has put -1622789957
Thread-1 has put -1010639133
A form Thread-0 0 null
A form Thread-1 -1010639133 name-1010639133
B from Thread-0 0 null
B from Thread-1 -1010639133 name-1010639133
这样改就行了:
private static ThreadLocal<MyThreadLocal> tl = new ThreadLocal<MyThreadLocal>();
//private static MyThreadLocal instance =null;
private MyThreadLocal(){}
public static MyThreadLocal getInstance()
{
MyThreadLocal instance = tl.get();
if(instance == null)
{
instance = new MyThreadLocal();
tl.set(instance);
}
return instance;
}作者: hello_world! 时间: 2012-10-21 16:31
忘记加上结果了:
Thread-0 has put -1824922109
A form Thread-0 -1824922109 name-1824922109
B from Thread-0 -1824922109 name-1824922109
Thread-1 has put -625868128
A form Thread-1 -625868128 name-625868128
B from Thread-1 -625868128 name-625868128作者: 汪小照 时间: 2012-10-21 20:00
hello_world! 发表于 2012-10-21 16:31
忘记加上结果了:
Thread-0 has put -1824922109
A form Thread-0 -1824922109 name-1824922109