Java ThreadLocal

参考URL:Java并发性和多线程介绍

 

1.初始化

初始化ThreadLocal对所有线程可见,set()方法设置的值只对当前线程可见。

private ThreadLocal myThreadLocal = new ThreadLocal<String>() {
   // 新建时覆写它的initialValue()方法,实现线程变量初始化,对所有线程都可见
   @Override protected String initialValue() {
       return "This is the initial value";
   }
};

2.一个完整的ThreadLocal示例

public class ThreadLocalExample {

    public static class MyRunnable implements Runnable {

        private ThreadLocal<Integer> threadLocal =
               new ThreadLocal<Integer>();

        @Override
        public void run() {
            threadLocal.set( (int) (Math.random() * 100D) );

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }

            System.out.println(threadLocal.get());
        }
    }

    public static void main(String[] args) {
        MyRunnable sharedRunnableInstance = new MyRunnable();
        /*
         * 两个线程使用相同的runable实例,
         * 但是由于是ThreadLocal对象,所以两个线程无法看到彼此的值,
         * 它们可以设置或者获取不同的值。
         */
        Thread thread1 = new Thread(sharedRunnableInstance);
        Thread thread2 = new Thread(sharedRunnableInstance);

        thread1.start();
        thread2.start();

        thread1.join(); 
        thread2.join(); 
    }

}

3.InheritableThreadLocal

ThreadLocal实例内部每个线程只能看到自己的私有值,InheritableThreadLocal允许一个线程创建的所有子线程访问其父线程的值,InheritableThreadLocal是ThreadLocal的一个子类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值