多线程基础知识第五篇:ThreadLocal的使用

ThreadLocal变量默认只能被当前线程访问。可以用于单个线程上下文信息的存储,如requestId。

1、先调用ThreadLocal的无参构造器,然后再调用set方法赋值,这种情况下,变量只能在当前线程访问,在其他线程访问不到,get返回null。

    public static void main(String[] args) throws InterruptedException {
        ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
        threadLocal.set(6);
        Thread t = new Thread(() -> {
            Integer i = threadLocal.get();
            System.out.println(i);
        });
        t.start();
        t.join();
    }

2、调用ThreadLocal的withInitial()静态方法给变量赋初始值,这样的话,这个变量就可以在所有线程中访问。

    public static void main(String[] args) throws InterruptedException {
        ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 6);
        Thread t = new Thread(() -> {
            Integer i = threadLocal.get();
            System.out.println(i);
        });
        t.start();
        t.join();
    }

3、使用ThreadLocal的子类InheritableThreadLocal,可以实现在子线程中访问父线程的变量

    public static void main(String[] args) throws InterruptedException {
        ThreadLocal<Integer> threadLocal = new InheritableThreadLocal<>();
        threadLocal.set(6);
        Thread t = new Thread(() -> {
            Integer i = threadLocal.get();
            System.out.println(i);
        });
        t.start();
        t.join();
    }

ThreadLocal的实现原理

get方法是先获取当前线程,然后获取当前线程的

posted on 2016-05-06 15:00  koushr  阅读(10027)  评论(0编辑  收藏  举报

导航