Test1
public class Test1 {
public static ThreadLocal<String> tt = new ThreadLocal<String>();
public static void main(String args[]) {
tt.set("xiaogao");
new Test2().print();
}
}Test2
public class Test2 {
public void print(){
System.out.println(Test1.tt.get());
}
} 现在可以打印“xiaogao”
修改后的Test2
public class Test2 {
public void print(){
new Thread(new Runnable(){
public void run(){
System.out.println(Test1.tt.get());
}
}).start();
}
}现在打印的却是null。查看set和get的方法第一句话都是Thread t = Thread.currentThread();可见他们是一个线程,如果像修改后的Test2,新new了一个线程,就取不到了。
10万+

被折叠的 条评论
为什么被折叠?



