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命令需要访问核心内存和各种文件,所 ...
随机推荐
- mac os x 把reids nignx mongodb做成随机启动吧
~/Library/LaunchAgents 由用户自己定义的任务项 /Library/LaunchAgents 由管理员为用户定义的任务项 /Library/LaunchDaemons 由管理员定义 ...
- docker基于本地模版导入创建镜像
/* 因为直接去网站拿会下载的慢,所以直接到网站里,对着此包--〉右键--〉复制链接地址 网站地址:https://openvz.org/Download/template/precreated */ ...
- Mysql 数据库学习笔记01查询
1.数据查询基本操作 * 正则表达式查询: 字段名 regexp '匹配方式', select * from user where username regexp '^名' -- 查询 姓名 名 ...
- [USACO06NOV]路障---严格次短路
Description 贝茜把家搬到了一个小农场,但她常常回到FJ的农场去拜访她的朋友.贝茜很喜欢路边的风景,不想那么快地结束她的旅途,于是她每次回农场,都会选择第二短的路径,而不象我们所习惯的那样, ...
- Highcharts创建一个简单的柱状图
新建一个html文件,将highcharts引入到你的页面后,通过两个步骤我们就可以创建一个简单的图表了. 1.创建div容器 在页面的 body部分创建一个div,并指定div 的 id,高度和宽度 ...
- Simplify Path——简单经典的预处理
Given an absolute path for a file (Unix-style), simplify it. For example,path = "/home/", ...
- Python3通过汉字输出拼音
https://github.com/mozillazg/python-pinyin # pip install pypinyin from pypinyin import pinyin, lazy_ ...
- [水煮 ASP.NET Web API2 方法论](12-4)OData 支持的 Function 和 Action
问题 在 Web API 中使用 OData Function 和 Action. 解决方案 可以通过 ODataModelBuilder,使用 OData 构建 ASP.NET Web API, E ...
- CSS3主要的几个样式笔记
1.边框:border-color: 设置对象边框的颜色. 使用CSS3的border-radius属性,如果你设置了border的宽度是X px,那么你就可以在这个border上使用X ...
- Java中分拣存储的demo
//Letter.java package yzhou.map; /** * * @author 洋 * */ public class Letter { private String name; ...