Simple use of ThreadLocal class

1. Overview
The sharing of variable values can be in the form that public is a static variable, and all threads use the same public static variable. For example, to implement shared variables within a thread, jdk provides ThreadLocal to solve this problem.

The main solution of ThreadLocal is to bind each thread with its own value. The ThreadLocal class can be regarded as a box for storing data globally.
2. Basic use

Basic demo demo (access value)

/**
 * @author Shanghai shangxuetang shsxt.com
 * Learn more about adding V: java8733
 */
public class ThreadLocalDemo01 {
    
    public static ThreadLocal t1 = new ThreadLocal();
    
    public static void main(String[] args) {
        
        if (t1.get() == null) {
            System.out.println("Never let go of value");
            t1.set("Stored value");
        }
        
        System.out.println(t1.get());
        System.out.println(t1.get());
        
    }
}

  

Example results:
Never let go of value
Stored value
Stored value

Results analysis:
When the t1.get() method is called for the first time, the returned null is returned. Then, the value is successfully retrieved after the value is assigned through the set() method.
ThreadLocal class solves the isolation of variables between different threads. That is, different threads have their own values. The values in different threads can be saved in ThreadLocal class.

3. Isolation
Verify the isolation of thread variables:

package com.threadlocal;
/**
 * Verify isolation
 * @author Shanghai shangxuetang shsxt.com
 *
 */
public class ThreadLocalDemo02 {

    public static ThreadLocal demo = new ThreadLocal();

    public static void main(String[] args) {

        ThreadA a = new ThreadA();
        a.start();

        ThreadB b = new ThreadB();
        b.start();
        try {
            for (int i = 0; i < 100; i++) {
                demo.set("Main .." + (i + 1));
                System.out.println("Main  getValue ..." + demo.get());

                Thread.sleep(200);
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

class ThreadA extends Thread {

    @Override
    public void run() {
        try {
            for (int i = 0; i < 100; i++) {

                ThreadLocalDemo02.demo.set("ThreadA" + (i + 1));
                System.out.println("ThreadA getValue " + ThreadLocalDemo02.demo.get());
                Thread.sleep(200);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        super.run();
    }

}

class ThreadB extends Thread {

    @Override
    public void run() {
        try {
            for (int i = 0; i < 100; i++) {

                ThreadLocalDemo02.demo.set("ThreadA" + (i + 1));
                System.out.println("ThreadA getValue " + ThreadLocalDemo02.demo.get());
                Thread.sleep(200);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        super.run();
    }

}

  

results of enforcement

Summary:
It can be seen from the above execution results that when each thread stores values to ThreadLocal, each thread takes out its own thread values. This also verifies the isolation of the thread variables.
Shanghai shangxuetang Java Teaching and research group original, reprint please indicate the source! Thank you for reading Shanghai shangxuetang Java Technical articles. Please pay more attention to collection!

Tags: Java JDK

Posted on Tue, 05 May 2020 14:27:57 -0400 by NoBullMan