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

How to create and access ThreadLocal in java

王林
Release: 2023-05-27 15:16:06
forward
715 people have browsed it

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();
Copy after login

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();
Copy after login

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”);
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template