当前位置:网站首页>线程数据共享和安全 -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); } */
}
}
边栏推荐
- Detailed explanation of pointer array and array pointer (comprehensive knowledge points)
- C language EXECL function
- 一文讲解发布者订阅者模式与观察者模式
- VMware vSphere 6.7 virtualization cloud management 12. Vcsa6.7 update vCenter server license
- 岭回归和lasso回归
- JUC学习
- PHP batch Excel to word
- Redis efficient like and cancel function
- Common interview questions for performance test
- gcc使用、Makefile总结
猜你喜欢

Let's just say I can use thousands of expression packs

安装VCenter6.7【VCSA6.7(vCenter Server Appliance 6.7) 】

彻底解决Lost connection to MySQL server at ‘reading initial communication packet

C#实现基于广度优先BFS求解无权图最短路径----完整程序展示

VMware vSphere 6.7 virtualization cloud management 12. Vcsa6.7 update vCenter server license

手把手带你了解一块电路板,从设计到制作(干货)

Basic concepts of database

servlet【初识】

Introduction to EtherCAT
Common interview questions for performance test
随机推荐
[machine learning] vectorized computing -- a must on the way of machine learning
【小程序项目开发--京东商城】uni-app之自定义搜索组件(上)
C#实现图的深度优先遍历--非递归代码
Complete training and verification of a neural network based on pytorch
【小程序项目开发 -- 京东商城】uni-app 商品分类页面(下)
Hal library operation STM32 serial port
[small program project development -- Jingdong Mall] the home page commodity floor of uni app
调试定位导航遇到的问题总结
A shooting training method based on the digital measurement of Joule energy and posture of sphygmomanometer air bag with standard air pressure
打包iso文件的话,怎样使用hybrid格式输出?isohybrid:command not found
Detailed explanation of pointer array and array pointer (comprehensive knowledge points)
[applet project development -- JD mall] uni app commodity classification page (Part 2)
Detailed list of errors related to twincat3 ads of Beifu
Introduction to webrtc concept -- an article on understanding source, track, sink and mediastream
限流组件设计实战
通信协议——分类及其特征介绍
Example of Huawei operator level router configuration | example of configuring optionc mode cross domain LDP VPLS
Redis分布式锁的8大坑
The best learning method in the world: Feynman learning method
[applet project development -- JD mall] uni app commodity classification page (first)