Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use ThreadLocal and ThreadPoolExecutor together

Shulou Source: shulou.com Published: 2022-06-01 18:18:35 10月03日 Update

This article mainly introduces how to use ThreadLocal and ThreadPoolExecutor at the same time, the article is very detailed, has a certain reference value, interested friends must read it!

ThreadLocal keeps a copy of member variables for each thread, while ThreadPoolExecutor is a group of threads that constantly perform various tasks (thread reuse). For example, if you ask a ThreadPoolExecutor with 3 threads to perform 13 tasks, one thread will perform 5 tasks and the other two threads will perform 4 tasks. Then, these few (5 or 4) tasks performed by each thread will share the data backup of ThreadLocal. Not every task has a copy of the data.

Come to a code description.

A ThreadLocal quantity such as sewNum is defined in the TestNum class, and each thread accesses the class with a copy of seqNum.

Define a task to print the value of the ThreadLocal variable

Perform 13 tasks in a thread pool with 3 threads

In the output, you can see that each thread has a backup of ThreadLocal data. But these tasks do not have separate copies of data (tasks performed by the same thread that share the same copy of data)

This is the reason for the sub-library BUG mentioned at the beginning of the article. Programmers get the illusion that every task has a copy of the data.

The above is all the content of the article "how to use ThreadLocal and ThreadPoolExecutor at the same time". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Threads tasks copies data at the same time content backup data backup articles constant two code value interest sublibraries reasons variables guys buddies that is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux MariaDB Shulou Information Redmi macOS