您的位置:首页 > 编程语言 > Java开发

Thread-Local Variables线程局部变量

2016-01-28 08:57 344 查看
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 类的每个实例描述一个线程局部变量,它是一个变量,提供一个单独的存储槽给每个访问这个变量的各个线程。你可以把一个线程局部变量看作是一个多槽变量,在其中,各个线程能在相同变量中存储一个不同值。各个线程只看见它的值并不知道其它线程在这个变量中有它们自己的值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息