Java ThreadLocal: Usage Guide
ThreadLocal class can be used to create thread-local variables, storing independent copies for each thread. These variables are only visible to the thread that creates them, and cannot be accessed by other threads. Here is a basic example of how to use the ThreadLocal class:
Create a ThreadLocal instance.
ThreadLocal<String> threadLocal = new ThreadLocal<>();
2. Assigning a value to the local variable of the current thread.
threadLocal.set("Hello, ThreadLocal!");
3. Accessing the value of local variables in the current thread:
String value = threadLocal.get();
System.out.println(value); // 输出:Hello, ThreadLocal!
Store independent copies of variables in each thread.
ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0); // 初始值为0
ExecutorService executor = Executors.newFixedThreadPool(2);
for (int i = 0; i < 2; i++) {
executor.submit(() -> {
int value = threadLocal.get();
value++;
threadLocal.set(value);
System.out.println("Thread " + Thread.currentThread().getId() + ": " + value);
});
}
executor.shutdown();
In the example above, we create a ThreadLocal object so that each thread has its own variable copy, increments the variable value, and outputs it to the console. The values for each thread are independent and do not affect each other.
In conclusion, the ThreadLocal class can be used in a multi-threaded environment to store thread-local variables, ensuring data isolation between threads and preventing thread safety issues.