ThreadLocal概念:线程局部变量 是一种多线程间并发访问变量的解决方案 与synchronized等加锁的方式不同 ThreadLocal完全不提供锁 而使用用空间换时间的手段 为每个线程提供变量的独立副本 以保障线程安全 从性能说 ThreadLocal不具有绝对的优势 在并发不是很高的时候 加锁的性能会更好 但作为一套与锁完全无关的线程安全解决方案 在高并发量或竞争激烈的场景 使用ThreadLocal可以在一定程度上减少锁竞争
下面给出一个demo
public class ConnThreadLocal {
public static ThreadLocal<String> th = new ThreadLocal<String>();
public void setTh(String value){
th.set(value);
}
public void getTh(){
System.out.println(Thread.currentThread().getName() + ":" + this.th.get());
}
public static void main(String[] args) throws InterruptedException {
final ConnThreadLocal ct = new ConnThreadLocal();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
ct.setTh("张三");
ct.getTh();
}
}, "t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
ct.getTh();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t2");
t1.start();
t2.start();
}
}
线程1设置threadLocal的值 在线程2中是获取不到的
threadlocal 底层就是hashmap 用法:
//当前线程共享同样的数据
public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();
productMapper.insert(product);
//mybatis-plus能自动获取到刚才这个数据的自增id
log.debug("刚才的商品的id:{}",product.getId());
threadLocal.set(product.getId());
.....
reduction.setProductId(threadLocal.get());
productFullReductionMapper.insert(reduction);
同一次调用,也就是同一个线程,只要上面方法的数据,下面要用。我们就可以用ThreadLocal共享数据 保证线程安全
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有