In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use the Synchronized thread-safe Synchronized keyword". In daily operations, I believe that many people have doubts about how to use the Java thread-safe Java keyword. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use the Java thread-safe Java keyword!" Next, please follow the editor to study!
1 Why is there a thread safety problem in multithreading?
The rational use of threads can improve the processing performance of the program, one is to use multi-core CPU to achieve parallel execution of threads, and the other is that asynchronous execution of threads can improve the throughput of the system.
Although threads have these advantages, they also bring a lot of problems. For example:
1.1 Security issues caused by shared variables
Let's take a look at a picture first:
A variable I, if thread An or thread B separately accesses and modifies the value of variable I without any problem, then if you modify variable I in parallel, there will be a security problem.
Then simulate this scenario with code, and in order to see the effect better, I use 100 threads:
Public class ThreadDemo1 {private static int i = 0; public static void inc () {try {Thread.sleep (1);} catch (InterruptedException e) {e.printStackTrace ();} iTunes;} public static void main (String [] args) throws InterruptedException {for (int I = 0; I)
< 100; i++) { new Thread(() ->ThreadDemo1.inc (). Start ();} Thread.sleep (1000); System.out.println ("run result" + I);}}
Output result:
eighty-eight
This output is not fixed, the first time it may be 88, the second time it may be 87, this result is not consistent with our expected result (the expected result is 100), so whether an object is thread-safe depends on whether it will be accessed by multiple threads and how the object is used in the program. If multiple threads access the same shared object, without additional synchronization and no other coordination of the caller code, the state of the shared object is still correct (correctness means that the result of the object is consistent with what we expect), which means that the object is thread-safe.
For thread safety, it essentially manages access to the data state, which is usually shared and mutable. Shared: means that the data variable can be accessed by multiple threads; variable: the value of the variable can be changed during its life cycle.
two。 How to ensure the data security of thread parallelism-Synchroinzed
In view of the above situation, how should we solve this problem? The first thing that comes to mind is a lock, and the lock must be mutually exclusive. For example, in the picture above, if thread An is changing the value of I, thread B cannot change the value of I. In other words, there is a thread safety problem when you modify the value of a shared variable in parallel, so if we don't let you do it in parallel, we will solve this problem. So java provides the Synchroinzed keyword.
2.1Basic understanding of Synchroinzed
Synchroinzed has been around for a long time, but it used to be a heavy lock, so it's good for people to use it. Synchroinzed is optimized in javaSE 1.6. biased locks and lightweight locks are introduced. Therefore, in the case of low concurrency, it is recommended to use Synchroinzed to add locks. Why is it recommended when the concurrency is not high, because if the concurrency is high, Synchroinzed will be upgraded to a heavy lock.
2.2 three locking methods for Synchroinzed
Modify the instance method. The lock is the current instance object. You need to obtain the lock of the current instance before entering the synchronization code.
Modify the static method. The lock is the class object of the current class. You need to obtain the lock of the current class object before entering the synchronization code.
Modify the code block, the lock is the object in parentheses, lock a given object, and obtain the lock of the given object before entering the synchronous code base.
Add Q group: 478052716 free (Java framework materials, video materials, BATJ interview materials)
Take a look at the simple code
Public class SynchroinzedDemo {/ * Lock static methods * / public static synchronized void test () {} / * Lock instance methods * / public synchronized void test1 () {} / * Lock code blocks * / public void test2 () {synchronized (this) {}
Then we implement synchronized locking with the above example:
Public class ThreadDemo1 {private static int i = 0; public static void inc () {synchronized (ThreadDemo1.class) {try {Thread.sleep (1);} catch (InterruptedException e) {e.printStackTrace ();} iTunes + }} public static void main (String [] args) throws InterruptedException {for (int I = 0; I)
< 100; i++) { new Thread(() ->ThreadDemo1.inc (). Start ();} Thread.sleep (1000); System.out.println ("run result" + I);}}
Running result:
Run result 100
Perfectly solve the thread safety problem caused by parallel modification of shared variables.
At this point, the study on "how to use the Java thread-safe Synchronized keyword" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.