Threadlocal is used for the following scenarios:
1. Resources that are not allowed to be accessed concurrently by multiple threads
2. Single thread survival process uses only one instance
The official definition is as follows:
Private static fields in classes this wish to associate state with a thread (e.g., a user ID or Transaction ID).
Examples of Use (official example: each thread has its own individual ID, and this ID remains self-increasing as new threads are added):
ImportJava.util.concurrent.atomic.AtomicInteger; Public classThreadId {//Atomic integer containing the next thread ID to be assigned Private Static FinalAtomicinteger NextID =NewAtomicinteger (0); //thread local variable containing each Thread ' s ID Private Static FinalThreadlocal<integer> threadId =NewThreadlocal<integer>() {@OverrideprotectedInteger InitialValue () {returnnextid.getandincrement (); } }; //Returns The current thread ' s unique ID, assigning it if necessary Public Static intget () {returnThreadid.get (); } }
This article is no longer detailed in the source code, interested students can read their own source code.
Reference:
Https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html
The threadlocal in Java uses