简体   繁体   English

java中的ThreadLocal

[英]ThreadLocal in java

This is the example in java doc for the ThreadLocal use. 这是Thread doc使用的java doc中的示例。

public class ThreadId {
 // Atomic integer containing the next thread ID to be assigned
 private static final AtomicInteger nextId = new AtomicInteger(0);

 // Thread local variable containing each thread's ID
 private static final ThreadLocal<Integer> threadId =
     new ThreadLocal<Integer>() {
         @Override protected Integer initialValue() {
             return nextId.getAndIncrement();
     }
 };

 // Returns the current thread's unique ID, assigning it if necessary
 public static int get() {
     return threadId.get();
 }
 }

i dont get the point that why we used threadlocal here. 我不明白为什么我们在这里使用threadlocal。 isnt AtomicInteger already thread safe? 是不是AtomicInteger已经线程安全?

what about changed the code to this? 把代码更改为这个怎么样?

public class ThreadId {
 // Atomic integer containing the next thread ID to be assigned
 private static final AtomicInteger nextId = new AtomicInteger(0);

 // Returns the current thread's unique ID, assigning it if necessary
 public static int get() {
     return nextId.getAndIncrement();
 }
 }

I also dont get what this means: 我也没有得到这意味着什么:

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. 这些变量与它们的正常对应物的不同之处在于,访问一个变量的每个线程(通过其get或set方法)都有自己独立初始化的变量副本。

So, is ThreadLocal (internally) holds an array of integer for each thread? 那么,ThreadLocal(内部)是否为每个线程保存一个整数数组? the Java_concurrency in practice mentioned that we can consider threadLocal as Map. 实践中的Java_concurrency提到我们可以将threadLocal视为Map。

Thanks in advanced. 提前致谢。

Notice how all these variables are declared static. 注意所有这些变量都是如何声明为static的。 That means there is normally only ever one. 这意味着通常只有一个。

To make threadId thread specific we use threadlocal. 为了使threadId线程特定,我们使用threadlocal。 Which means instead of there being one instance there will now be one instance per thread. 这意味着每个线程现在只有一个实例,而不是有一个实例。

In your version each time we call get() it will return a different number. 在您的版本中,每次调用get()时,它都会返回不同的数字。

In the original version the first time get is called it will initialise itself and save the value on the thread. 在原始版本中,第一次调用get时,它将自动初始化并将值保存在线程上。 This value will be returned for each subsequent call to get on that thread. 每次后续调用都会返回此值以获取该线程。

your code 你的代码

//in thread 0
ThreadId.get() //return 0
//in thread 1
ThreadId.get() //return 1
//in thread 0
ThreadId.get() //return 2
//in thread 1
ThreadId.get() //return 3
//in thread 0
ThreadId.get() //return 4

original code 原始代码

//in thread 0
ThreadId.get() //return 0
//in thread 1
ThreadId.get() //return 1
//in thread 0
ThreadId.get() //return 0
//in thread 1
ThreadId.get() //return 1
//in thread 0
ThreadId.get() //return 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM