Home  >  Article  >  Java  >  How to create and access ThreadLocal in java

How to create and access ThreadLocal in java

王林
王林forward
2023-05-27 15:16:06681browse

1. Create. Each thread can only access the value set by calling the set() method of ThreadLocal.

The ThreadLocal object is instantiated. Although all threads can access this ThreadLocal instance, each thread can only access the value it sets by calling the set() method of ThreadLocal, even if two different threads set different values ​​on the same ThreadLocal object. They also have no access to each other's values.

private ThreadLocal myThreadLocal = new ThreadLocal();

2. When accessing , when the get method returns to the Object object, the set() object needs to input parameters of the Object type.

String threadLocalValue = (String) myThreadLocal.get();

Once the ThreadLocal variable is created, you can set a value that needs to be saved through the following code:

myThreadLocal.set("A thread local value”);

What collection classes are there in Java?

Collections in Java Mainly divided into four categories:

1. List: ordered and repeatable;

2. Queue: ordered and repeatable;

3 , Set collection: non-repeatable;

4. Map mapping: unordered, the key is unique, and the value is not unique.

The above is the detailed content of How to create and access ThreadLocal in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete