当前位置:网站首页>线程数据共享和安全 -ThreadLocal
线程数据共享和安全 -ThreadLocal
2022-07-01 03:10:00 【Al_tair】
ThreadLocal
大家好呀,我是小笙!这部分是我学习ThreadLocal的笔记
线程数据共享和安全 - ThreadLocal
概述
ThreadLocal是一个将在多线程中为每一个线程创建单独的变量副本的类; 当使用ThreadLocal来维护变量时, ThreadLocal会为每个线程创建单独的变量副本, 避免因多线程操作共享变量而导致的数据不一致的情况
每一个 ThreadLocal 对象,只能为当前线程关联一个数据,如果要为当前线程关联多个数 据,就需要使用多个 ThreadLocal 对象实例

代码示例

public class Dog {
}
// ThreadLocalDemo
public class ThreadLocalDemo implements Runnable{
public static ThreadLocal<Object> threadLocal= new ThreadLocal<>();
public static void main(String[] args) {
// 创建进程
new Thread(new ThreadLocalDemo()).start();
}
@Override
public void run() {
Dog dog = new Dog();
threadLocal.set(dog);
System.out.println("ThreadLocalDemo: " + Thread.currentThread().getName());
new Service().update();
}
}
// Service
public class Service {
public void update() {
Object o = ThreadLocalDemo.threadLocal.get();
System.out.println(o.getClass()); // threadLocal.Dog
String name = Thread.currentThread().getName();
System.out.println("在 Service 的 update() 线程 name= " + name);
new Dao().update();
}
}
// Dao
public class Dao {
public void update() {
Object o = ThreadLocalDemo.threadLocal.get();
System.out.println(o.getClass()); // threadLocal.Dog
String name = Thread.currentThread().getName();
System.out.println("在 Dao 的 update() 线程是= " + name);
}
}
源码分析
// ThreadLocal.get()方法
public T get() {
// 获取当前进程t
Thread t = Thread.currentThread();
// 从容器map中获取该线程的threadLocals
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();
}
// ThreadLocal.set(数据)方法
public void set(T value) {
// 获取当前进程t
Thread t = Thread.currentThread();
// 从容器map中获取该线程的threadLocals
ThreadLocalMap map = getMap(t);
/* ThreadLocalMap getMap(Thread t) { return t.threadLocals; } */
if (map != null) {
// 如果存在,则覆盖该 threadLocals对象对应的原来数据(可以是对象)
map.set(this, value);
} else {
// 如果不存在,则创建t.threadLocals,存入ThreadLocalMap对象
// key:this(调用该方法的threadLocal对象)value:需要存入的数据
createMap(t, value);
/* void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); } */
}
}
边栏推荐
- 岭回归和lasso回归
- Redis 教程
- 调试定位导航遇到的问题总结
- Completely solve the lost connection to MySQL server at 'reading initial communication packet
- [reading notes] copywriting realization -- four golden steps for writing effective copywriting
- 手把手带你了解一块电路板,从设计到制作(干货)
- LeetCode_ Stack_ Difficulties_ 227. basic calculator (excluding multiplication and division)
- Edge Drawing: A combined real-time edge and segment detector 翻译
- [us match preparation] complete introduction to word editing formula
- [linear DP] longest common subsequence
猜你喜欢

POI exports excel and displays hierarchically according to parent-child nodes

Const and the secret of pointers

如何校验两个文件内容是否相同

Huawei operator level router configuration example | configuration optionA mode cross domain LDP VPLS example

Chapter 03_ User and authority management

终极套娃 2.0 | 云原生交付的封装

Detailed list of errors related to twincat3 ads of Beifu

STM32 - DS18B20 temperature sampling of first-line protocol
![[small program project development -- Jingdong Mall] the home page commodity floor of uni app](/img/80/20bed20a6ab91e82ad6800b11f2caa.png)
[small program project development -- Jingdong Mall] the home page commodity floor of uni app

通信协议——分类及其特征介绍
随机推荐
Redis分布式锁的8大坑
Latest interface automation interview questions
[reading notes] copywriting realization -- four golden steps for writing effective copywriting
Elk elegant management server log
js 找出两个数组中的重复元素
Subnet division and subnet summary
Detailed list of errors related to twincat3 ads of Beifu
串口接收数据方案设计
VMware vSphere 6.7 virtualization cloud management 12. Vcsa6.7 update vCenter server license
几行事务代码,让我赔了16万
Metadata in NFT
Borrowing constructor inheritance and composite inheritance
最新接口自动化面试题
JS to find duplicate elements in two arrays
gcc使用、Makefile总结
EtherCAT原理概述
HTB-Lame
性能测试常见面试题
POI导出excel,按照父子节点进行分级显示
最好用的信任关系自动化脚本(shell)