Find out exactly what Java Concurrency six: ThreadLocal

A, ThreadLocal Profile

ThreadLocal stored in a variable manner with the binding thread, each thread with its own security isolation ThreadLocalMap variables, provides a new way to solve the problem of concurrent multi-threaded programs. ThreadLocal not to solve multiple threads access a shared variable, but create a separate copy of the variable for each thread, a method for maintaining objects and avoid the complexity of the parameters passed. It is by way of using space for time to resolve the conflict access the same variable multiple threads.

In ThreadLocal class has a static inner class ThreadLocalMap (which is similar to the Map), in the form of key-value pairs for each storing a copy of the variable thread, key elements in the current ThreadLocalMap ThreadLocal object, a copy of the variable value corresponding to the threads, each there may be multiple threads ThreadLocal. Examples of the ThreadLocalMap member variable is online layer Thread class, each thread has its own separate ThreadLocalMap, through this variable to store a plurality of ThreadLocal (Key) values ​​corresponding thereto.

Brief, will understand the following look at an example:

Create two ThreadLocal variable threadLocal1 and threadLocal2, respectively, in the three threads threadLocal variable value 1,2,3,4,5,6 following code.

public class MyTest {
    static ThreadLocal<Integer>

Guess you like

Origin blog.csdn.net/u013277209/article/details/103321178