The ThreadLocal class in Java ensures that the variables you create can only be read and written by the same thread. Therefore, even if two threads are executing the same code, and that code has a reference to a ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variable.
Creating a ThreadLocal
Here is a code showing how to create a ThreadLocal:
private ThreadLocal myThreadLocal = new ThreadLocal();
As you can see Yes, you instantiate a new ThreadLocal object. This only needs to be done once per thread. Even if different threads execute the same code that accesses a ThreadLocal, each thread will only see its own ThreadLocal instance. Even if two threads set different values on the same ThreadLocal object, they will not see each other's values.
Accessing a ThreadLocal
Once a ThreadLocal is created, you can set a value to store like this:
myThreadLocal.set("A thread local value");
You can read this value like this:
String threadLocalValue = (String) myThreadLocal.get();
This get method returns an object, and this set method passes an object as a parameter.
Generic ThreadLocal
You can create a generic ThreadLocal so that you don’t have to do it when calling the get method Forced conversion. Here is an example:
private ThreadLocal<String> myThreadLocal = new ThreadLocal<String>();
Now you can only store string types in ThreadLocal instances. In addition, you do not need to force conversion of this value:
myThreadLocal.set("Hello ThreadLocal"); String threadLocalValue = myThreadLocal.get();
Initialize the ThreadLocal value
Because setting the value of a ThreadLocal object It is only visible to the thread that sets this value, so no thread can use the set method to set the ThreadLocal value to be visible to all threads.
Instead, you can subclass ThreadLocal to specify an initial value for a ThreadLocal object, and override the initialValue method. Like this:
private ThreadLocal myThreadLocal = new ThreadLocal<String>() { @Override protected String initialValue() { return "This is the initial value"; } };
Now all threads can see the same initialization value before calling the set method.
Complete ThreadLocal instance
Here is a fully running ThreadLocal instance
public class ThreadLocalExample { public static class MyRunnable implements Runnable { private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>(); @Override public void run() { threadLocal.set( (int) (Math.random() * 100D) ); try { Thread.sleep(2000); } catch (InterruptedException e) { } System.out.println(threadLocal.get()); } } public static void main(String[] args) { MyRunnable sharedRunnableInstance = new MyRunnable(); Thread thread1 = new Thread(sharedRunnableInstance); Thread thread2 = new Thread(sharedRunnableInstance); thread1.start(); thread2.start(); thread1.join(); //wait for thread 1 to terminate thread2.join(); //wait for thread 2 to terminate } }
This example creates a separate MyRunnable instance, which is passed to two different threads. Both threads executed the run method and set different values on the ThreadLocal instance. If the call to this set method is synchronous and it does not use a ThreadLocal object, the second thread will overwrite the value set by the first thread.
However, because it is a ThreadLocal object, they cannot see each other's values. Therefore, they set and get different values.
InheritableThreadLocal
This InheritableThreadLocal class is a subclass of the ThreadLocal class. Instead of each thread having its own value inside a ThreadLoca, this class allows access to the value for one thread and all child threads created by that thread.
The above is the content of Java local thread (ThreadLocal). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

Atom editor mac version download
The most popular open source editor

SublimeText3 Chinese version
Chinese version, very easy to use