不同线程不能获取其他线程设置的ThreadLocal里面的值

背景:

最近在项目用到了ThreadLocal,存放一些值。起线程异步获取ThreadLocal中的值,得到null。这是由于,ThreadLocal.get()会获取当前线程的一个map对象,以ThreadLocal为key获取对象。

demo:

这里定义了一个Person类,使用两个线程,一个向threadlocal set(),两个线程都使用threadLocal.get()获取存放的对象

其中一个线程没有获取到值

/**
 * Created by GuanXF on 2017/12/8.
 */
public class ThreadLocalTest {
    private static ThreadLocal<Person> personThreadLocal = new ThreadLocal<Person>();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                Person gxf = new Person("Gxf", 18);
                personThreadLocal.set(gxf);
                System.out.println("From threadlocal : " + personThreadLocal.get());
            }
        });
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                System.out.println("From threadlocal : " + personThreadLocal.get());
            }
        });
        t1.start();
        t1.join();
        t2.start();

    }

    //Person实体类
    static class Person{
        private String name;
        private int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = 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;
        }
        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}

 

posted on 2017-12-09 00:05  luckygxf  阅读(900)  评论(0编辑  收藏  举报

导航