Home  >  Article  >  Java  >  Java local thread (ThreadLocal)

Java local thread (ThreadLocal)

黄舟
黄舟Original
2017-02-28 10:52:492172browse

The ThreadLocal class in Java ensures that the variables you create can only be read and written by the same thread. Therefore, even if two threads are executing the same code, and that code has a reference to a ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variable.

Creating a ThreadLocal

Here is a code showing how to create a ThreadLocal:

private ThreadLocal myThreadLocal = new ThreadLocal();


As you can see Yes, you instantiate a new ThreadLocal object. This only needs to be done once per thread. Even if different threads execute the same code that accesses a ThreadLocal, each thread will only see its own ThreadLocal instance. Even if two threads set different values ​​on the same ThreadLocal object, they will not see each other's values.

Accessing a ThreadLocal

Once a ThreadLocal is created, you can set a value to store like this:

myThreadLocal.set("A thread local value");

You can read this value like this:

String threadLocalValue = (String) myThreadLocal.get();

This get method returns an object, and this set method passes an object as a parameter.

Generic ThreadLocal

You can create a generic ThreadLocal so that you don’t have to do it when calling the get method Forced conversion. Here is an example:

private ThreadLocal<String> myThreadLocal = new ThreadLocal<String>();

Now you can only store string types in ThreadLocal instances. In addition, you do not need to force conversion of this value:

myThreadLocal.set("Hello ThreadLocal");

String threadLocalValue = myThreadLocal.get();


Initialize the ThreadLocal value

Because setting the value of a ThreadLocal object It is only visible to the thread that sets this value, so no thread can use the set method to set the ThreadLocal value to be visible to all threads.

Instead, you can subclass ThreadLocal to specify an initial value for a ThreadLocal object, and override the initialValue method. Like this:


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


Now all threads can see the same initialization value before calling the set method.

Complete ThreadLocal instance

Here is a fully running ThreadLocal instance

public class ThreadLocalExample {


    public static class MyRunnable implements Runnable {

        private ThreadLocal<Integer> threadLocal =
               new ThreadLocal<Integer>();

        @Override
        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();

        thread1.join(); //wait for thread 1 to terminate
        thread2.join(); //wait for thread 2 to terminate
    }

}

This example creates a separate MyRunnable instance, which is passed to two different threads. Both threads executed the run method and set different values ​​on the ThreadLocal instance. If the call to this set method is synchronous and it does not use a ThreadLocal object, the second thread will overwrite the value set by the first thread.

However, because it is a ThreadLocal object, they cannot see each other's values. Therefore, they set and get different values.

InheritableThreadLocal

This InheritableThreadLocal class is a subclass of the ThreadLocal class. Instead of each thread having its own value inside a ThreadLoca, this class allows access to the value for one thread and all child threads created by that thread.

The above is the content of Java local thread (ThreadLocal). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
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