This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).
For example, the class below generates unique identifiers local to each thread. A thread's id is assigned the first time it invokes UniqueThreadIdGenerator.getCurrentThreadId() and remains unchanged on subsequent calls.
先看两个例子:
1.
结果:
Thread-0:2
Thread-0:3
Thread-1:2
Thread-1:5
Thread-1:6
Thread-1:7
Thread-1:8
Thread-0:4
Thread-0:9
Thread-0:10
10------
2.
结果:
Thread-1:1
Thread-1:2
Thread-1:3
Thread-1:4
Thread-1:5
Thread-0:1
Thread-0:2
Thread-0:3
Thread-0:4
Thread-0:5
0------
从以上两个例子看出: ThreadLocal为每个线程创建一个ThreadLocal<Integer> a我副本,每个线程各自操作自己的那个副本, 不会影响其它线程的副本......