Java ThreadLocal use

https://www.jianshu.com/p/74f1a883da50

 

ThreadLocal class allows us to create variables can only be read in the same thread. Therefore, if a piece of code ThreadLocal variable contains a reference, even if two threads simultaneously execute this code, they can not access each other's ThreadLocal variable.

1. How to create a ThreadLocal variable
The following code shows three ways to create a ThreadLocal variables:
1: Direct to create objects
private ThreadLocal myThreadLocal = new ThreadLocal();
Second way: create a generic Object
private ThreadLocal myThreadLocal = new ThreadLocal<String>();
Three ways: create and initialize the value of generic objects

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

By code instantiates a ThreadLocal object. We only need to instantiate an object once, and it does not need to know which thread is instantiated. While all of the threads can access to this ThreadLocal instance, but each thread can only access to their own values set by calling the set ThreadLocal () method. Even the two different values in different threads on the same ThreadLocal object is set up, they still can not access each other's values.
When creating ThreadLocal objects, we can specify generic, so we do not use every get () method returns the value for the cast; and we can set the initial value.

2. How to access ThreadLocal variables
Once a ThreadLocal variable is created, you can set a value needs to be saved through the following code:
myThreadLocal.set("初始值”);
you can read the value stored in the ThreadLocal variables by the following method:
String threadLocalValue = (String) myThreadLocal.get();
GET () method returns an Object object, set () object needs to pass a parameter of type Object.


3. Test Code

public class Test {

    private static ThreadLocal<String> threadLocal;

    public static void main(String[] args) {

        threadLocal = new ThreadLocal<String>() {

            @Override
            protected String initialValue() {
                return "初始化值";
            }

        };
        
        for (int i = 0; i < 10; i++){
            new Thread(new MyRunnable(), "线程"+i).start();
        }

    }

    public static class MyRunnable implements Runnable {

        @Override
        public void run() {
            String name = Thread.currentThread().getName();
            System.out.println(name + "的threadLocal"+ ",设置为" + name);
            threadLocal.set(name);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {}
            System.out.println(name + ":" + threadLocal.get());
        }

    }

}

Print Results:

线程1的threadLocal,设置为线程1
线程4的threadLocal,设置为线程4
线程3的threadLocal,设置为线程3
线程2的threadLocal,设置为线程2
线程0的threadLocal,设置为线程0
线程6的threadLocal,设置为线程6
线程5的threadLocal,设置为线程5
线程7的threadLocal,设置为线程7
线程8的threadLocal,设置为线程8
线程9的threadLocal,设置为线程9
线程3:线程3
线程4:线程4
线程8:线程8
线程6:线程6
线程2:线程2
线程5:线程5
线程9:线程9
线程1:线程1
线程7:线程7
线程0:线程0

 

Guess you like

Origin blog.csdn.net/zhuchunyan_aijia/article/details/93618650