Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use ThreadLocal and ThreadPoolExecutor together

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report