本帖最后由 汪小照 于 2012-10-22 10:32 编辑
- import java.util.Random;
- /*
- * 当有多个数据时,将其封装成对象,
- * 存放的是对象,而不再是单个数据。
- */
- public class ThreadScopeShareDate1 {
- public static void main(String [] args)
- {
- for(int x=0;x<2;x++)
- {
- new Thread(new Runnable(){
- public void run()
- {
- int data = new Random().nextInt();
- System.out.println(Thread.currentThread()
- .getName()+" has put "+ data);
- MyThreadLocal mtl = MyThreadLocal.getInstance();
- mtl.setAge(data);
- mtl.setName("name"+ data);
- new A().get();
- new B().get();
- }
- }).start();
- }
- }
- static class A{
- public void get()
- {
- MyThreadLocal mtl = MyThreadLocal.getInstance();
- 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
打印出来的竟然有0 和null ,而张老师讲课时运行多次都不会有0 和 null 的结果,有知道的请分析一下哪里出错了,错误的原因是什么? |