Java – can each thread have a unique static variable?

I have a static variable and I want each thread to be unique

Is this the case with all static variables? Or there is no guarantee That is, do threads occasionally update the static variable values in main memory or keep them for themselves?

If this cannot be guaranteed, are there any types of static and thread unique variables in Java? What is essentially a thread's global, but hides other threads?

Solution

I think you're looking for Java ThreadLocal

Please note that if you do thread pooling, this may cause you trouble, because you may think you are getting a new thread and starting a new process from it, but what happens is that you reuse a thread data to complete other work, so there is surplus. It is difficult to debug when they occur in the field

Here is a tutorial on using ThreadLocal

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>