java  中ThreadLocal实例分析

 更新时间:2017年06月15日 08:38:53   转载 投稿:lqh  
这篇文章主要介绍了java 中ThreadLocal实例分析的相关资料,需要的朋友可以参考下

java  中ThreadLocal实例分析

从概念上理解,threadlocal使变量在多个线程中相互隔离实现线程安全,threadlocal包装的变量最终都专属于对应的每个线程,线程之间相互独立,用一个具体实现来说明:

public interface Consumer {
  int consume();
}
public class ComsumeThread implements Runnable {

  private Consumer consumer;

  public ComsumeThread(Consumer consumer) {
    this.consumer = consumer;
  }

  @Override
  public void run() {
    for(int i=0;i<10;i++){
      System.out.println(Thread.currentThread().getName()+" After Consume left:"+consumer.consume());
    }

  }
}
public class ConsumeClientA implements Consumer {

  private static int leftNum = 30;

  @Override
  public int consume() {
    int orgLeftNum = leftNum;
    Random random = new Random(System.currentTimeMillis());
    try {
      Thread.sleep(random.nextInt(3));
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    orgLeftNum = orgLeftNum -1;
    leftNum = orgLeftNum;
    return leftNum;
  }

  public static void main(String[] args){
    Consumer consumer = new ConsumeClientA();
    Thread thread1 = new Thread(new ComsumeThread(consumer));
    Thread thread2 = new Thread(new ComsumeThread(consumer));
    Thread thread3 = new Thread(new ComsumeThread(consumer));

    thread1.start();
    thread2.start();
    thread3.start();
  }
}

ConsumeClientA是在没有做任何线程安全处理,结果如下:

Thread-2 After Consume left:29
Thread-1 After Consume left:29
Thread-3 After Consume left:29
Thread-2 After Consume left:28
Thread-1 After Consume left:28
Thread-3 After Consume left:28
Thread-2 After Consume left:27
Thread-1 After Consume left:27
Thread-2 After Consume left:26
Thread-3 After Consume left:27
Thread-1 After Consume left:25
Thread-2 After Consume left:25
Thread-3 After Consume left:25
Thread-1 After Consume left:24
Thread-2 After Consume left:24
Thread-3 After Consume left:24
Thread-1 After Consume left:23
Thread-2 After Consume left:23
Thread-3 After Consume left:23
Thread-1 After Consume left:22
Thread-2 After Consume left:22
Thread-3 After Consume left:22
Thread-1 After Consume left:21
Thread-2 After Consume left:21
Thread-3 After Consume left:21
Thread-1 After Consume left:20
Thread-2 After Consume left:20
Thread-3 After Consume left:20
Thread-1 After Consume left:19
Thread-3 After Consume left:18

增加threadlocal处理,每个线程相互独立,实现如下:

public class ConsumeClientB implements Consumer {
  private ThreadLocal<Integer> leftNumThreadLocal = new ThreadLocal<Integer>(){
    @Override
    protected Integer initialValue() {
      return 30;
    }
  };

  @Override
  public int consume() {
    int orgLeftNum = leftNumThreadLocal.get();
    Random random = new Random(System.currentTimeMillis());
    try {
      Thread.sleep(random.nextInt(3));
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    orgLeftNum = orgLeftNum -1;
    leftNumThreadLocal.set(orgLeftNum);
    return leftNumThreadLocal.get();
  }

  public static void main(String[] args){
    Consumer consumer = new ConsumeClientB();
    Thread thread1 = new Thread(new ComsumeThread(consumer));
    Thread thread2 = new Thread(new ComsumeThread(consumer));
    Thread thread3 = new Thread(new ComsumeThread(consumer));

    thread1.start();
    thread2.start();
    thread3.start();
  }
}

运行的结果如下:

Thread-1 After Consume left:29
Thread-3 After Consume left:29
Thread-2 After Consume left:29
Thread-1 After Consume left:28
Thread-3 After Consume left:28
Thread-2 After Consume left:28
Thread-1 After Consume left:27
Thread-3 After Consume left:27
Thread-2 After Consume left:27
Thread-1 After Consume left:26
Thread-3 After Consume left:26
Thread-2 After Consume left:26
Thread-1 After Consume left:25
Thread-3 After Consume left:25
Thread-2 After Consume left:25
Thread-1 After Consume left:24
Thread-3 After Consume left:24
Thread-2 After Consume left:24
Thread-1 After Consume left:23
Thread-3 After Consume left:23
Thread-2 After Consume left:23
Thread-1 After Consume left:22
Thread-3 After Consume left:22
Thread-2 After Consume left:22
Thread-1 After Consume left:21
Thread-3 After Consume left:21
Thread-2 After Consume left:21
Thread-1 After Consume left:20
Thread-3 After Consume left:20
Thread-2 After Consume left:20

每个线程拥有自己的独立变量,相互隔离实现线程安全。

那ThreadLocal是怎样实现这种线程隔离的线程安全的呢?

从ThreadLocal源码可以看到,真正实现线程隔离,与线程挂钩的,其实是ThreadLocal.ThreadLocalMap这个实现类,最明显的体现就在于Thread类源码的这样一个变量申明说明了ThreadLocal.ThreadLocalMap与Thread的关系:

ThreadLocal.ThreadLocalMap threadLocals, inheritableThreadLocals;

Thread类是包含threadLocals对象的,ThreadLocal的具体实现就是根据提供的get,set等接口,对当前thread的threadLocals变量进行相关操作的,如get操作代码如下:

  public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
      ThreadLocalMap.Entry e = map.getEntry(this);
      if (e != null)
        return (T)e.value;
    }
    return setInitialValue();
  }

  ThreadLocal.ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
  }

可以看到,getMap()方法就是从当前thread获取对应的threadLocals变量,然后从这个ThreadLocal.ThreadLocalMap类型的threadLocals变量中获取对应线程中该ThreadLocal对象对应的变量值。

set方法的操作也是一样:

  public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocal.ThreadLocalMap map = getMap(t);
    if(map != null) {
      map.set(this, value);
    } else {
      this.createMap(t, value);
    }

  }

  void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
  }

static class Entry extends WeakReference<ThreadLocal> {
      Object value;

      Entry(ThreadLocal var1, Object var2) {
        super(var1);
        this.value = var2;
      }
    }

ThreadLocalMap中存的是内部类Entry的数组,Entry是继承WeakReference实现,WeakReference的好处是保存对象引用,而又不干扰该对象被GC回收,线程执行完回收threadLocals变量时不会受到Entry封装的变量的干扰。

而且ThreadLocalMap中的key是ThreadLocal,所以一个ThreadLocal对象只能在一个Thread对象中保存一个ThreadLocal的value。

综上,很多人说ThreadLocal的实现是ThreadLocalMap中存Thread对象为key,变量为value的map结构,其实是错误的。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

  • echarts图表导出excel示例

    echarts图表导出excel示例

    这篇文章主要介绍了echarts图表导出excel示例,需要的朋友可以参考下
    2014-04-04
  • 浅谈java指令重排序的问题

    浅谈java指令重排序的问题

    下面小编就为大家带来一篇浅谈java指令重排序的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • why在重写equals时还必须重写hashcode方法分享

    why在重写equals时还必须重写hashcode方法分享

    首先我们先来看下String类的源码:可以发现String是重写了Object类的equals方法的,并且也重写了hashcode方法
    2013-10-10
  • Java5种遍历HashMap数据的写法

    Java5种遍历HashMap数据的写法

    这篇文章主要介绍了Java5种遍历HashMap数据的写法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-03-03
  • java实现FTP文件上传与文件下载

    java实现FTP文件上传与文件下载

    这篇文章主要为大家详细介绍了java实现FTP文件上传与文件下载的相关资料,通过以下两种方式实现,通过JDK自带的API实现,二是通过Apache提供的API是实现,感兴趣的小伙伴们可以参考一下
    2016-04-04
  • Java从同步容器到并发容器的操作过程

    Java从同步容器到并发容器的操作过程

    这篇文章主要介绍了Java从同步容器到并发容器的操作过程,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2018-10-10
  • 详解SpringMVC的类型转换及验证方法

    详解SpringMVC的类型转换及验证方法

    在本篇文章里面我们给大家详细分析了SpringMVC的类型转换及验证方法的相关知识,对此有需要的朋友们学习下吧。
    2018-10-10
  • java基于servlet的文件异步上传

    java基于servlet的文件异步上传

    本篇文章主要介绍了java基于servlet的文件异步上传,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
    2016-10-10
  • java实现的冒泡排序算法示例

    java实现的冒泡排序算法示例

    这篇文章主要介绍了java实现的冒泡排序算法,结合实例形式分析了冒泡排序算法的具体操作步骤与实现技巧,需要的朋友可以参考下
    2017-01-01
  • Spring配置shiro时自定义Realm中属性无法使用注解注入的解决办法

    Spring配置shiro时自定义Realm中属性无法使用注解注入的解决办法

    今天小编就为大家分享一篇关于Spring配置shiro时自定义Realm中属性无法使用注解注入的解决办法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-03-03

最新评论