The design concept and function of ThreadLocal

The ThreadLocal class in Java allows us to create variables that can only be read and written by the same thread. Therefore, if a piece of code contains a reference to a ThreadLocal variable, even if two threads execute the code at the same time, they cannot access each other's ThreadLocal variable.

1. How to create a ThreadLocal variable The following code shows how to create a ThreadLocal variable:

private ThreadLocal myThreadLocal = new ThreadLocal(); 1 We can see that a ThreadLocal object is instantiated through this code. We only need to instantiate the object once, and we don't need to know which thread it was instantiated from. Although all threads can access this ThreadLocal instance, each thread can only access the value set by itself by calling the set() method of ThreadLocal. Even if two different threads set different values ​​on the same ThreadLocal object, they still cannot access each other's values.

2. How to access ThreadLocal variables Once you have created a ThreadLocal variable, you can set a value that needs to be saved with the following code:

myThreadLocal.set("A thread local value"); 1 The value stored in the ThreadLocal variable can be read by the following methods:

String threadLocalValue = (String) myThreadLocal.get(); 1 The get() method returns an Object object, and the set() object needs to pass in an Object type parameter.

3. Specify a generic type for ThreadLocal We can create a ThreadLocal object with a specified generic type, so that we don't need to cast the value returned by the get() method every time. The following shows an example of a ThreadLocal specifying a generic type:

private ThreadLocal myThreadLocal = new ThreadLocal<String>(); 1 Now we can only store values ​​of type String into the ThreadLocal object.

And we don't need to cast when we get the value from ThreadLocal.

4. How to initialize the value of the ThreadLocal variable Since the value set in the ThreadLocal object can only be accessed by the thread that set the value, the thread cannot use the set() method on the ThreadLocal object to save an initial value, and this initial value can be used by all access to the thread.

But we can specify an initial value for a ThreadLocal object by creating a subclass of ThreadLocal and overriding the initialValue() method. As shown in the code below:

private ThreadLocal myThreadLocal = new ThreadLocal<String>() { @Override protected String initialValue() { return "This is the initial value"; }

}; 1 2 3 4 5 6 7 A Complete ThreadLocal Example The following is a complete executable ThreadLocal example:

public class ThreadLocalExample {

public static class MyRunnable implements Runnable {

 private ThreadLocal threadLocal = new ThreadLocal()
    [@Override](https://my.oschina.net/u/1162528)

    public void run() {

        threadLocal.set((int) (Math.random() * 100D));

       try {

      Thread.sleep(2000);

        } catch (InterruptedException e) {
        }
        System.out.println(threadLocal.get());
    }
}


public static void main(String[] args) {
     MyRunnable sharedRunnableInstance = new MyRunnable();
     Thread thread1 = new Thread(sharedRunnableInstance);
     Thread thread2 = new Thread(sharedRunnableInstance);
     thread1.start();
     thread2.start();

}

} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 The above example creates an instance of MyRunnable and passes that instance as a parameter to two threads. The two threads execute the run() method separately, and both save different values ​​on the ThreadLocal instance. If they don't access a ThreadLocal object and the call to set() is synchronized, the second thread will overwrite the value set by the first thread. However, since they are accessing a ThreadLocal object, neither thread can see the value saved by the other. That is, they access two different values.

About InheritableThreadLocal The InheritableThreadLocal class is a subclass of the ThreadLocal class. Unlike ThreadLocal, where each thread has its own value, InheritableThreadLocal allows a thread and all child threads created by that thread to access its stored value.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325338913&siteId=291194637