In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "what is the safety of threads?" in the operation of actual cases, many people will encounter such a dilemma, and then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Step 1: stateless classes
Here we write a simple thread-safe class. How simple is it? As shown below
Public class SafeDemo {public int sum (int n, int m) {return n + m;}}
It's that simple. We say this class is thread-safe.
Why is it safe?
Because this class has no state, that is, a stateless class
Only the local variable NJM, which exists in the stack, is unique to each thread, and the heap is shared only if it is not shared with other threads.
Therefore, when each thread operates sum, the corresponding NMagne m is only visible to itself, so of course it is safe.
Well, through the example above, we know what a thread-safe class is, so that's the end of this section. Goodbye.
In the above example, we give a stateless class, and then let's add a state to try.
Step 2: add a state variable
Add a state variable (static attribute) with the following code
Public class UnSafeDemo {static int a = 0; public static void main (String [] args) throws InterruptedException {/ / Thread 1 new Thread (())-> {for (int jung0 for j {for (int job0) J {for (int junio j {for (int jung0 witch j {for (int jung0 witch j)
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.