Home > Java > javaTutorial > body text

Java uses the get() function of the ThreadLocal class to obtain the value of thread local variables

PHPz
Release: 2023-07-24 14:40:52
Original
1835 people have browsed it

Java uses the get() function of the ThreadLocal class to obtain the value of thread local variables

In concurrent programming, multiple threads may access the same variable, and thread safety issues need to be considered. In order to solve this problem, Java provides the ThreadLocal class, which can achieve data isolation between threads, thereby ensuring that each thread has its own copy of variables. In the ThreadLocal class, we can use the get() function to obtain the local variable value of the current thread.

Before using the ThreadLocal class, we first understand the difference between local variables and global variables. Global variables are variables that can be accessed throughout the execution of the program, while local variables can only be accessed within the block of code in which they are defined. There may be thread safety issues when accessing global variables, but this problem does not exist for local variables.

The following is a simple example to demonstrate how to use the get() function of the ThreadLocal class to obtain the value of a thread local variable.

public class ThreadLocalDemo {
    private static final ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        // 创建并启动两个线程
        Thread thread1 = new Thread(new MyRunnable());
        Thread thread2 = new Thread(new MyRunnable());
        thread1.start();
        thread2.start();
    }

    public static class MyRunnable implements Runnable {
        @Override
        public void run() {
            // 设置线程局部变量的值
            threadLocal.set((int) (Math.random() * 100));

            // 输出当前线程局部变量的值
            System.out.println("ThreadLocal value in " + Thread.currentThread().getName() + ": " + threadLocal.get());

            // 线程睡眠一段时间
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 输出当前线程局部变量的值(再次)
            System.out.println("ThreadLocal value in " + Thread.currentThread().getName() + " after sleep: " + threadLocal.get());

            // 清除线程局部变量
            threadLocal.remove();
        }
    }
}
Copy after login

The above code first creates a ThreadLocal object to store the local variables of each thread. In the run() method of MyRunnable, we set the local variable value of the current thread to a random number by calling the set() function of the ThreadLocal object.

Then, we get the local variable value of the current thread by calling the get() function of the ThreadLocal object and output it to the console.

To increase the effectiveness of the example, we let them sleep for 1 second in each thread. Call the get() function again and find that even after sleeping, the local variable value of each thread is still the random number just set.

Finally, we clear the local variables of the current thread by calling the remove() function of the ThreadLocal object.

Run the above code, you can see output similar to the following:

ThreadLocal value in Thread-0: 42
ThreadLocal value in Thread-1: 96
ThreadLocal value in Thread-0 after sleep: 42
ThreadLocal value in Thread-1 after sleep: 96
Copy after login

You can see that the local variable value of each thread is isolated between different threads and does not affect each other.

By using the get() function of the ThreadLocal class, we can easily obtain the local variable value of the current thread, thereby simplifying variable sharing and thread synchronization operations in concurrent programming.

The above is the detailed content of Java uses the get() function of the ThreadLocal class to obtain the value of thread local variables. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template