ThreadLocal study test notes

ThreadLocal study test notes

Different threads get the current thread through the Thread.currentThread() method

The set method uses the current thread as the key and the value is placed in the ThreadLocalMap to distinguish different threads

The get method uses the current thread as the key to find the corresponding value in the map

public static void main(String[] args) throws InterruptedException {
    
    

        ThreadLocal threadLocal = new ThreadLocal();
        Thread a = new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                System.out.println(threadLocal.get());
                threadLocal.set(1);
                System.out.println(threadLocal.get());
            }
        });
        Thread b = new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                System.out.println(threadLocal.get());
                threadLocal.set(2);
                System.out.println(threadLocal.get());
            }
        });
        a.start();
        a.join();
        b.start();

 }
null
1
null //重点
2

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/qq_41454682/article/details/107447561