JAVA的Thread局部变量ThreadLocal

本文详细介绍了ThreadLocal类,它是Java中实现线程局部变量的关键。通过ThreadLocal,每个线程能够拥有独立的变量副本,实现线程间的隔离。文章还解释了其四个核心方法:get()、initialValue()、remove() 和 set() 的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ThreadLocal:    Thread局部变量-------ThreadLocalVariable

java.lang 
Class ThreadLocal<T>
java.lang.Object
  java.lang.ThreadLocal<T>
Direct Known Subclasses:
InheritableThreadLocal
public class ThreadLocal<T>
extends Object
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread

ThreadLocal为每个线程使用该变量的线程提供一个独立的副本,这样每个副本读可以独立改变自己的副本,不受其他线程的影响


这个类有四个方法:

Method Summary

 T get() 
          Returns the value in the current thread's copy of this thread-local variable.

//返回当前线程对应的局部变量的值
protected  T initialValue() 
          Returns the current thread's initial value for this thread-local variable.

       //返回该线程变量的初始值,缺省值返回null,protected修饰,便于子类覆盖,是一个延迟调用,当第一次调用set(),get()时才执行1次
 void remove() 
          Removes the value for this ThreadLocal.

//删除当前局部变量的值
 void set(T value) 
          Sets the current thread's copy of this thread-local variable to the specified value.

//设置当前线程局部变量的值:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值