Thread-Local Variables线程局部变量

You will sometimes want to associate per-thread data (such a user ID) with a thread. Although you
can accomplish this task with a local variable, you can only do so while the local variable exists. You
could use an instance field to keep this data around longer, but then you would have to deal with
synchronization. Thankfully, Java supplies ThreadLocal as a simple (and very handy) alternative.
Each instance of the ThreadLocal class describes a thread-local variable, which is a variable that
provides a separate storage slot to each thread that accesses the variable. You can think of a
thread-local variable as a multislot variable in which each thread can store a different value in the
same variable. Each thread sees only its value and is unaware of other threads having their own

values in this variable.

你有时想要将每个线程数据(如一个用户ID)和一个线程关联起来。虽然你可以用一个局部变量来完成此事,但当此局部变量存在的时候,你只能这么做。你可以使用一个字段(大概是longer)来保持这个数据, 但是然后你得处理同步。谢天谢地,Java提供ThreadLocal 作为一个简单(并且非常顺手)的替代方案。 ThreadLocal 类的每个实例描述一个线程局部变量,它是一个变量,提供一个单独的存储槽给每个访问这个变量的各个线程。你可以把一个线程局部变量看作是一个多槽变量,在其中,各个线程能在相同变量中存储一个不同值。各个线程只看见它的值并不知道其它线程在这个变量中有它们自己的值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值