In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you the Java multi-threaded synchronized synchronization code block example analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!
1. Which is better, synchronization method or synchronization block?
Synchronous blocks are better, which means that code outside the synchronous block is executed asynchronously, which is more efficient than synchronizing the entire method. Please know one principle: the smaller the scope of synchronization, the better.
For small critical sections, we set the synchronized synchronization keyword directly in the method declaration to avoid the problem of race conditions. But for larger critical section code segments, for the sake of execution efficiency, it is best to divide the synchronization method into small critical section code segments.
Public class TwoPlus {private int num1 = 0; private int num2 = 0; public synchronized void plus (int val1,int val2) {this.num1 = num1+val1; this.num2 = num2+val2;}}
The critical section code snippet contains operations on two critical section resources, sum1 and sum2, respectively. After plus (int val1,int val2) is synchronized with synchronized, the thread that enters the critical section code segment has the operation rights of sum1 and sum2, and is fully occupied. Once the thread enters, when the thread is operating sum1 but not sum2, it also occupies the operation right of sum2 in vain. Because other threads do not enter the critical section, they can only watch the sum2 idle and can not perform the operation.
Therefore, if synchronized is added to the method, if the critical section code segment protected by it contains more than one critical section resource, it will cause idle waiting of the critical section resources, which in turn will affect the throughput of the critical section code segment. To improve throughput, you can put the synchronized keyword inside the function to synchronize a block of code. The synchronized synchronization block is written as follows:
Synchronized (syncObject) {/ / Code Block of critical Section Code snippet}
In parentheses after the synchronized synchronization block is a syncObject object, which means that you need to acquire a monitor lock for a syncObject object to enter the critical section code snippet. Because every Java object has a monitor lock, any Java object can be used as a synchronization lock for synchronized.
Use the synchronized synchronization block to improve the throughput of the above TwoPlus class. The specific code is as follows:
Public class TwoPlus {private int num1 = 0; private int num2 = 0; / / two different lock objects private Object object1 = new Object (); private Object object2 = new Object (); public void plus (int val1,int val2) {synchronized (object1) {this.num1 = num1+val1;} synchronized (object2) {this.num2 = num2+val2;}
After the transformation, the addition operations of two independent critical area resources sum1 and sum2 can be executed concurrently, and at a certain time, different threads can add sum1 and sum2 at the same time, which improves the throughput of plus () method.
What is the difference between the synchronized method and the synchronized synchronization block?
Generally speaking, the synchronized method is a coarse-grained concurrency control, and only one thread can execute the synchronized method at a time, while the synchronized code block is a fine-grained concurrency control, and other code outside the synchronized block can be accessed concurrently by multiple threads. In a method, not all code is a critical section code segment, and only a few lines of code may involve thread synchronization issues. So the synchronized code block controls the synchronous access of multiple threads more finely than the synchronized method.
The synchronization lock of the synchronized method essentially uses a this object lock, which eliminates the need to manually set the synchronization lock. Using synchronized code blocks requires manual setting of synchronization locks.
2. Synchronized synchronization code block public class RoomDemo {private static int count = 0; / / create lock object. Synchronization code block needs to manually set object lock private static Object object = new Object (); public static void main (String [] args) throws InterruptedException {Thread T1 = new Thread (()-> {for (int iTun0) I {/ / use the object object to lock the critical section resource for (int iTuno object I {synchronized (object) {System.out.println ("thread T1 is executing"); / / endless loop while (count==1) {}, "T1") Thread T2 = new Thread (()-> {synchronized (object) {System.out.println ("Thread T2 is executing"); count--;}}, "T2"); t1.start (); t2.start (); t1.join (); t2.join ();}}
Execution result:
You can see that thread T1 executes an endless loop, so every time the thread context switches, thread T2 is blocked, unable to get the lock, and therefore cannot be executed.
If we create an exception during thread execution:
Public class ExceptionDemo {private static int count = 1; / / create lock object private static Object object = new Object (); public static void main (String [] args) throws InterruptedException {Thread T1 = new Thread (()-> {synchronized (object) {System.out.println ("Thread T1 is executing") While (count==1) {/ / Integer.parseInt ("a");}, "T1"); Thread T2 = new Thread (()-> {synchronized (object) {System.out.println ("Thread T2 is executing") Count--;}, "T2"); t1.start (); t2.start (); t1.join (); t2.join ();}}
Execution result:
When the thread holding the lock object is executing the code in the synchronization code fast, if an exception occurs, the lock is released, so that thread T2 can get the lock object to execute the code in its own synchronization code block.
The above is all the contents of the article "sample Analysis of synchronized synchronization Code Block for Java multithreading". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more 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.
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.