ThreadLocal用法详解和原理(转)
本文转自https://www.cnblogs.com/coshaho/p/5127135.html 感谢作者
一、用法
ThreadLocal用于保存某个线程共享变量:对于同一个static ThreadLocal,不同线程只能从中get,set,remove自己的变量,而不会影响其他线程的变量。
1、ThreadLocal.get: 获取ThreadLocal中当前线程共享变量的值。
2、ThreadLocal.set: 设置ThreadLocal中当前线程共享变量的值。
3、ThreadLocal.remove: 移除ThreadLocal中当前线程共享变量的值。
4、ThreadLocal.initialValue: ThreadLocal没有被当前线程赋值时或当前线程刚调用remove方法后调用get方法,返回此方法值。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
package com.coshaho.reflect;/** * ThreadLocal用法 * @author coshaho * */public class MyThreadLocal{ private static final ThreadLocal<Object> threadLocal = new ThreadLocal<Object>(){ /** * ThreadLocal没有被当前线程赋值时或当前线程刚调用remove方法后调用get方法,返回此方法值 */ @Override protected Object initialValue() { System.out.println("调用get方法时,当前线程共享变量没有设置,调用initialValue获取默认值!"); return null; } }; public static void main(String[] args) { new Thread(new MyIntegerTask("IntegerTask1")).start(); new Thread(new MyStringTask("StringTask1")).start(); new Thread(new MyIntegerTask("IntegerTask2")).start(); new Thread(new MyStringTask("StringTask2")).start(); } public static class MyIntegerTask implements Runnable { private String name; MyIntegerTask(String name) { this.name = name; } @Override public void run() { for(int i = 0; i < 5; i++) { // ThreadLocal.get方法获取线程变量 if(null == MyThreadLocal.threadLocal.get()) { // ThreadLocal.et方法设置线程变量 MyThreadLocal.threadLocal.set(0); System.out.println("线程" + name + ": 0"); } else { int num = (Integer)MyThreadLocal.threadLocal.get(); MyThreadLocal.threadLocal.set(num + 1); System.out.println("线程" + name + ": " + MyThreadLocal.threadLocal.get()); if(i == 3) { MyThreadLocal.threadLocal.remove(); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static class MyStringTask implements Runnable { private String name; MyStringTask(String name) { this.name = name; } @Override public void run() { for(int i = 0; i < 5; i++) { if(null == MyThreadLocal.threadLocal.get()) { MyThreadLocal.threadLocal.set("a"); System.out.println("线程" + name + ": a"); } else { String str = (String)MyThreadLocal.threadLocal.get(); MyThreadLocal.threadLocal.set(str + "a"); System.out.println("线程" + name + ": " + MyThreadLocal.threadLocal.get()); } try { Thread.sleep(800); } catch (InterruptedException e) { e.printStackTrace(); } } } }<strong>}</strong> |
运行结果如下:
调用get方法时,当前线程共享变量没有设置,调用initialValue获取默认值!线程IntegerTask1: 0调用get方法时,当前线程共享变量没有设置,调用initialValue获取默认值!线程IntegerTask2: 0调用get方法时,当前线程共享变量没有设置,调用initialValue获取默认值!调用get方法时,当前线程共享变量没有设置,调用initialValue获取默认值!线程StringTask1: a线程StringTask2: a线程StringTask1: aa线程StringTask2: aa线程IntegerTask1: 1线程IntegerTask2: 1线程StringTask1: aaa线程StringTask2: aaa线程IntegerTask2: 2线程IntegerTask1: 2线程StringTask2: aaaa线程StringTask1: aaaa线程IntegerTask2: 3线程IntegerTask1: 3线程StringTask1: aaaaa线程StringTask2: aaaaa调用get方法时,当前线程共享变量没有设置,调用initialValue获取默认值!线程IntegerTask2: 0调用get方法时,当前线程共享变量没有设置,调用initialValue获取默认值!线程IntegerTask1: 0 |
二、原理
线程共享变量缓存如下:
Thread.ThreadLocalMap<ThreadLocal, Object>;
1、Thread: 当前线程,可以通过Thread.currentThread()获取。
2、ThreadLocal:我们的static ThreadLocal变量。
3、Object: 当前线程共享变量。
我们调用ThreadLocal.get方法时,实际上是从当前线程中获取ThreadLocalMap<ThreadLocal, Object>,然后根据当前ThreadLocal获取当前线程共享变量Object。
ThreadLocal.set,ThreadLocal.remove实际上是同样的道理。
关于ThreadLocalMap<ThreadLocal, Object>弱引用问题:
当线程没有结束,但是ThreadLocal已经被回收,则可能导致线程中存在ThreadLocalMap<null, Object>的键值对,造成内存泄露。(ThreadLocal被回收,ThreadLocal关联的线程共享变量还存在)。
虽然ThreadLocal的get,set方法可以清除ThreadLocalMap中key为null的value,但是get,set方法在内存泄露后并不会必然调用,所以为了防止此类情况的出现,我们有两种手段。
1、使用完线程共享变量后,显示调用ThreadLocalMap.remove方法清除线程共享变量;
2、JDK建议ThreadLocal定义为private static,这样ThreadLocal的弱引用问题则不存在了。
-------------------------------
基本原理
线程本地变量是和线程相关的变量,一个线程则一份数据。我们通过ThreadLocal保存的数据最终是保存在Thread类的ThreadLocalMap threadLocals变量中。ThreadlocalMap是一个Map结构,其中key为我们声明的ThreadLocal对象,value即为我们使用ThreadLocal保存的线程本地变量.
当我们调用ThreadLocal变量set方法时,那么为将TheadLocal作为key,set方法的参数做为value保存在当前线程的threadLocals中.调用get方法时类似,调用get方法时,会去Thread的threadLocals中去寻找key为ThreadLocal 变量的值
源码如下:
//Thread.threadLocals变量声明
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class.
*/
ThreadLocal.ThreadLocalMap threadLocals = null;
// ThreadLocal set get方法
/**
* 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);// getMap方法即去获取当前线程的ThreadLocalMap变量。
if (map != null)
map.set(this, value);//以this(ThreadLocal本身)为Key,参数value为值进行保存
else
createMap(t, value);
}
/**
* 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;
}
/**
* 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();
}
下面是测试代码:
static ThreadLocal<String> stringThreadLocal = new ThreadLocal<>();
@Test
public void test01(){
Thread thread1 = new Thread(){
@Override
public void run() {
stringThreadLocal.set("threadName===>"+Thread.currentThread().getName());
System.out.println(this.getName()+" thread get the value:"+stringThreadLocal.get());
}
};
Thread thread2 = new Thread(){
@Override
public void run() {
stringThreadLocal.set("threadName===>"+Thread.currentThread().getName());
System.out.println(this.getName()+" thread get the value:"+stringThreadLocal.get());
}
};
Thread thread3 = new Thread(){
@Override
public void run() {
stringThreadLocal.set("threadName===>"+Thread.currentThread().getName());
System.out.println(this.getName()+" thread get the value:"+stringThreadLocal.get());
}
};
thread1.start();
thread2.start();
thread3.start();
System.out.println("main线程调用set方法之前:"+stringThreadLocal.get());
stringThreadLocal.set("main 线程set的值");
System.out.println("main线程调用set方法之后:"+stringThreadLocal.get());
}
可以看到不同线程设置的值在该线程是能够正确的取到。由于Thread的threadLocals变量只能在Thread所在的包下才能够访问,因此不能对该变量进行直接访问以验证设置的值在Thread.currentThread对象里面。但如果你调试以上代码,设置值之后访问Thread.currentThread.threadLocals会看到之前设置的值。其中key为声明的ThreadLocal对象。
ThreadLocal用法详解和原理(转)的更多相关文章
- ThreadLocal用法详解和原理
一.用法 ThreadLocal用于保存某个线程共享变量:对于同一个static ThreadLocal,不同线程只能从中get,set,remove自己的变量,而不会影响其他线程的变量. 1.Thr ...
- ThreadLocal类详解:原理、源码、用法
以下是本文目录: 1.从数据库连接探究 ThreadLocal 2.剖析 ThreadLocal 源码 3. ThreadLocal 应用场景 4. 通过面试题理解 ThreadLocal 1.从数据 ...
- es6的promise用法详解
es6的promise用法详解 promise 原理 promise是es6的异步编程解决方案, 是es6封装好的对象: 一个promise有三种状态:Pending(进行中).Resolved(已完 ...
- JS逗号运算符的用法详解
逗号运算符的用法详解 注意: 一.由于目前正在功读JavaScript技术,所以这里拿JavaScript为例.你可以自己在PHP中试试. 二.JavaScript语法比较复杂,因此拿JavaScri ...
- jQuery 事件用法详解
jQuery 事件用法详解 目录 简介 实现原理 事件操作 绑定事件 解除事件 触发事件 事件委托 事件操作进阶 阻止默认事件 阻止事件传播 阻止事件向后执行 命名空间 自定义事件 事件队列 jque ...
- 1:CSS中一些@规则的用法小结 2: @media用法详解
第一篇文章:@用法小结 第二篇文章:@media用法 第一篇文章:@用法小结 这篇文章主要介绍了CSS中一些@规则的用法小结,是CSS入门学习中的基础知识,需要的朋友可以参考下 at-rule ...
- Java语言Socket接口用法详解
Socket接口用法详解 在Java中,基于TCP协议实现网络通信的类有两个,在客户端的Socket类和在服务器端的ServerSocket类,ServerSocket类的功能是建立一个Serve ...
- js原生之scrollTop、offsetHeight和offsetTop等属性用法详解
scrollTop.offsetHeight和offsetTop等属性用法详解:标题中的几个相关相关属性在网页中有这大量的应用,尤其是在运动框架中,但是由于有些属性相互之间的概念比较混杂或者浏览器兼容 ...
- lsof 命令用法详解
lsof 命令用法详解 作用 用于查看你进程开打的文件,打开文件的进程,进程打开的端口(TCP.UDP).找回/恢复删除的文件.是十分方便的系统监视工具,因为lsof命令需要访问核心内存和各种文件,所 ...
随机推荐
- mui 选项卡与header文字同步
mui底部tab固定 头部nav可变 <!DOCTYPE html> <html> <head> <meta charset="utf-8" ...
- canvas制作柱形图/折线图/饼状图,Konva写动态饼状图
制作饼状图 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...
- mysql utf8改utf8mb4
由于需要用到utf8mb4,之前是utf8现在给改成utf8mb4 查看当前环境 SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' ...
- tornado 模版继承 函数和类的调用
模版继承.函数和类的调用 目录结构 lesson5.py # -*- coding:utf-8 -*- import tornado.web import tornado.httpserver imp ...
- Windows + IDEA 手动开发MapReduce程序
参见马士兵老师的博文:map_reduce 环境配置 Windows本地解压Hadoop压缩包,然后像配置JDK环境变量一样在系统环境变量里配置HADOOP_HOME和path环境变量.注意:hado ...
- Python Flask SQLALchemy基础知识
一.介绍 SQLAlchemy是一个基于Python实现的ORM框架.该框架建立在 DB API之上,使用关系对象映射进行数据库操作,简言之便是:将类和对象转换成SQL,然后使用数据API执行SQL并 ...
- 基于rest_framework和redis实现购物车的操作,结算,支付
前奏: 首先,要在主机中安装redis,windows中安装,下载一个镜像,直接进行下一步的安装,安装成功后,在cmd中输入redis-cli 安装python的依赖库: redis 和 ...
- WP集成七牛云存储(原创)
借助:七牛镜像存储 WordPress 插件 https://wordpress.org/plugins/wpjam-qiniu/ 安装本插件1.4.5及以上版本,请先安装并激活WPJAM BASIC ...
- 怎么WordPress增加在线投稿功能
现在很多个人博客为了增加博客的内容,都会提供投稿通道,大部分都是以邮箱的形式进行投稿,不过这样一来,也很费人力,要拷贝复制,然后编辑等.如果给博客加个在线投稿功能,那就方便多了.稍微审核下文章内容就可 ...
- Jmeter------查看JSON Extractor获取的值
在接口的使用中,我们会经常用到上个接口response中的值作为下个接口的参数来使用,因此我们为了确保值的正确性,需要知道上个接口返回的值是否正确,因此我们使用到了如下的方法来查看返回值. 1.首先在 ...