Java local thread (ThreadLocal)
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)!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
