Java中的ThreadLocal是用来创建线程本地变量用的。我们都知道,访问某个对象的所有线程都是能够共享对象的状态的,所以这个对象状态就不是线程安全的。开发者可以通过使用同步来保证线程安全,但是如果不希望使用同步的话,我们也可以使用ThreadLocal变量。

Java ThreadLocal

其实每个线程都有自己的ThreadLocal变量,并且这个变量可以通过get()set()方法来获取默认值,或者修改其值。

ThreadLocal实例可以配置为静态私有变量来关联线程的状态。

Java ThreadLocal举例

下面的例子展示了在Java程序中如何使用ThreadLocal,也同时证实了,线程中都保留一份ThreadLocal的拷贝的。

package com.sapphire.threads;

import java.text.SimpleDateFormat;
import java.util.Random; public class ThreadLocalExample implements Runnable{ // SimpleDateFormat is not thread-safe, so give one to each thread
// SimpleDateFormat is not thread-safe, so give one to each thread
private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
@Override
protected SimpleDateFormat initialValue()
{
return new SimpleDateFormat("yyyyMMdd HHmm");
}
}; public static void main(String[] args) throws InterruptedException {
ThreadLocalExample obj = new ThreadLocalExample();
for(int i=0 ; i<10; i++){
Thread t = new Thread(obj, ""+i);
Thread.sleep(new Random().nextInt(1000));
t.start();
}
} @Override
public void run() {
System.out.println("Thread Name= "+Thread.currentThread().getName()+" default Formatter = "+formatter.get().toPattern());
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
} formatter.set(new SimpleDateFormat()); System.out.println("Thread Name= "+Thread.currentThread().getName()+" formatter = "+formatter.get().toPattern());
}
}

上面程序的输出结果类似下面的结果:

Thread Name= 0 default Formatter = yyyyMMdd HHmm
Thread Name= 1 default Formatter = yyyyMMdd HHmm
Thread Name= 0 formatter = M/d/yy h:mm a
Thread Name= 2 default Formatter = yyyyMMdd HHmm
Thread Name= 1 formatter = M/d/yy h:mm a
Thread Name= 3 default Formatter = yyyyMMdd HHmm
Thread Name= 4 default Formatter = yyyyMMdd HHmm
Thread Name= 4 formatter = M/d/yy h:mm a
Thread Name= 5 default Formatter = yyyyMMdd HHmm
Thread Name= 2 formatter = M/d/yy h:mm a
Thread Name= 3 formatter = M/d/yy h:mm a
Thread Name= 6 default Formatter = yyyyMMdd HHmm
Thread Name= 5 formatter = M/d/yy h:mm a
Thread Name= 6 formatter = M/d/yy h:mm a
Thread Name= 7 default Formatter = yyyyMMdd HHmm
Thread Name= 8 default Formatter = yyyyMMdd HHmm
Thread Name= 8 formatter = M/d/yy h:mm a
Thread Name= 7 formatter = M/d/yy h:mm a
Thread Name= 9 default Formatter = yyyyMMdd HHmm
Thread Name= 9 formatter = M/d/yy h:mm a

从代码中我们可以看到,10个线程都共享同一个对象,引用的是同一个ThreadLocal<SimpleDateFormat> formatter,看上面的代码,当线程0执行了formatter.set(new SimpleDateFormat())的时候,显然,读取的线程2的formatter仍然是默认的formatter,说明修改公共的formatter其实并没有生效,从每个线程单独来看,也没有破坏线程的安全性。

ThreadLocal原理

到了这里,很多人会奇怪,ThreadLocal的实现方式,下面我们来看下ThreadLocal的实现方案,首先看下这个其set和get方法的实现方案:

    /**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
*
* @return the current thread's value of this thread-local
*/
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
} /**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}

get和set方法中都有一个核心的概念,就是ThreadLocalMap其实,这个Map是根据线程绑定的,参考如下代码:

    /**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}

上面的代码是ThreadLocal中的getMap(Thread t)方法,这个方法来返回绑定到线程上的线程本地变量。线程的内部其实都会维护ThreadLocalMap的。通过前面的set和get方法,那么我们就知道ThreadLocal的实现方案了。ThreadLocalMap本质上,是一个HashMap,从线程到类型T的一个映射。这也就解释了,为什么我们将ThreadLocal定义为static final仍然不会影响线程的安全,因为我们之前代码中访问到的formatter其实都已经扔到了ThreadLocalMap里面,这样,每次调用get,其实会通过Thread.currentThread()找到对应的ThreadLocalMap,进而找到对应的formmater副本,调用set方法改变的都是ThreadLocalMap里面的值,自然就不会影响到我们在ThreadLocalExample之中的formatter变量,自然也就不存在线程安全问题。

同时,这也解释了我们为什么ThreadLocal的变量定义为了static final的,因为就算定义为非static的,仍然是没有任何意义的,只会增加额外的内存而已,因为我们本质上修改的不是ThreadLocalExample中的实例,而是ThreadLocalMap中的副本,所以定义为static final正合适。

ThreadLocal本质上其实是将一些变量副本写入Thread当中的,所以内存占用会更大,开发者可以根据自己的需求考虑是通过同步或者ThreadLocal的方式来实现线程安全操作。

Java线程和多线程(七)——ThreadLocal的更多相关文章

  1. java基础解析系列(七)---ThreadLocal原理分析

    java基础解析系列(七)---ThreadLocal原理分析 目录 java基础解析系列(一)---String.StringBuffer.StringBuilder java基础解析系列(二)-- ...

  2. Java线程与多线程教程

    本文由 ImportNew - liken 翻译自 Journaldev.   Java线程是执行某些任务的轻量级进程.Java通过Thread类提供多线程支持,应用可以创建并发执行的多个线程. 应用 ...

  3. Java线程和多线程(十三)——Callable,Future,FutureTask

    在Java多线程之中,Callable和Future的使用时非常广泛的.在之前的文章中,我们了解了关于Java线程池基础的一些内容,知道如何提交Runnable的任务.但是,Runnable的任务是无 ...

  4. Java线程和多线程(十二)——线程池基础

    Java 线程池管理多个工作线程,其中包含了一个队列,包含着所有等待被执行的任务.开发者可以通过使用ThreadPoolExecutor来在Java中创建线程池. 线程池是Java中多线程的一个重要概 ...

  5. Java线程和多线程(三)——线程安全和同步

    线程安全在Java中是一个很重要的课题.Java提供的多线程环境支持使用Java线程.我们都知道多线程共享一些对象实例的话,可能会在读取和更新共享数据的事后产生数据不一致问题. 线程安全 之所以会产生 ...

  6. Java线程和多线程(一)——线程的基本概念

    Java 线程是一个轻量级执行任务的处理单元.Java提供了Thread类来支持多线程,开发者在应用中可以创建多个线程来支持并发执行任务. 在应用中存在两种类型的线程,用户线程和守护线程.当我们启动应 ...

  7. Java 线程与多线程

    Java是一门支持多线程的编程语言! 什么是进程? 计算机中内存.处理器.IO等资源操作都要为进程进行服务. 一个进程上可以创建多个线程,线程比进程更快的处理单元,而且所占用的资源也小,多线程的应用也 ...

  8. Java线程和多线程(八)——Thread Dump

    Java的Thread Dump就是列出JVM中所有激活状态的线程. Java Thread Dump Java Thread Dump在分析应用性能瓶颈和死锁的时候,是非常有效的. 下面将介绍多种不 ...

  9. java线程跟多线程

    java创建线程两种方式: 1.继承Thread创建线程 /** * Created by lsf on 16/4/18. */ class NewThread extends Thread { Ne ...

随机推荐

  1. Java笔记 —— this 关键字

    Java笔记 -- this 关键字 h2{ color: #4ABCDE; } a{ color: blue; text-decoration: none; } a:hover{ color: re ...

  2. SpringCloud的学习记录(7)

    这一章节讲zuul的使用. 在我们生成的Demo项目上右键点击New->Module->spring Initializr, 然后next, 填写Group和Artifact等信息, 这里 ...

  3. centos7按报错dracut

    在Windows下,将从CentOS官网上下载的CentOS7镜像文件,用UltrISO以硬盘镜像方法写入U盘 安装过程中出现下面错误: dracut-initqueue[624]:Warning: ...

  4. 然之协同系统3.5(OA+CRM+CASH+TEAM)

    平台: Ubuntu 类型: 虚拟机镜像 软件包: mariadb-server 10.0.25 nginx 1.10.0 php7.0.4 collaboration commercial crm ...

  5. Linux改变文件属性与权限

    chgrp:改变文件所属用户组 chown:改变文件所有组 chmod:改变文件的权限 一.chgrp(change group的简称) 修改文件所属组:eg:chgrp users install. ...

  6. CFG的定义

    最近在CMU上NLP,好吧 对于见了很多年的CFG(Context-Free Grammar)发现又搞不懂是什么了 教材上写的是: mathematical system for modeling c ...

  7. 页面dom事件防止失效的一种写法

    经常我们写事件是这样的 $('.day').on('click', function () { some(); }); 但是这样在spa模式下经常容易出现页面切换后事件失效的问题, 可以采用这样的写法 ...

  8. Buffer实例

    互联网的基础是数据的传送,一切都围绕着数据展开,比如发送啊,接收啊,这一切都离不开网络,通过之前,学会了通过http模块来搭建一个服务器,也实现了网络爬虫,nodejs中网络的部分,Net这个模块,对 ...

  9. 预处理-04-#if defined和#if !defined

    因为对于一个大程序而言,我们可能要定义很多常量( 不管是放在源文件还是头文件 ),那么我们有时考虑定义某个常量时,我们就必须返回检查原来此常量是否定义,但这样做很麻烦. if defined 宏正是为 ...

  10. spring boot1.5.6 测试类

    package com.qutaoyao.demo.web; import com.qutaoyao.demo.web.controller.HelloController;import org.ju ...