Deep understanding of the difference between using the synchronized synchronization method and synchronizing code blocks

Source: Internet
Author: User

I. Differences between code blocks and methods

First you need to know what the difference is between a block of code and a method:

Constructors and method blocks, where constructors can be overloaded, which means that they can be created by different constructors when creating an object, the constructor belongs to the object, and the code block is initialized for all objects. Below is a look at the following:

 Public classConstructor_methodblock {Private intnum; PrivateString str; //Constructors     PublicConstructor_methodblock (intnum,string str) {System.out.println ("\n************ Constructor ****************"); System.out.println ("The value of the member variable before entering the constructor is num:" + This. num+ "STR:" + This. Str);  This. str=str;  This. num=num; System.out.println ("After assignment num is" +num+ "str is" +str); }    //Method Block{System.out.println ("\n************ code block ****************"); System.out.println ("The value of the member variable before entering the method block is num:" +num+ "str:" +str); Num=1; STR= "Li"; System.out.println ("After assignment num is" +num+ "str is" +str); }     Public Static voidMain (string[] args) {NewConstructor_methodblock (2, "Fei"); }}

The result is:

The code block is found to be executed earlier than the constructor, and the block of code is performed by all objects.

Now that we have a certain understanding of code blocks and methods, what are the drawbacks of synchronous methods that require us to synchronize blocks of code?

Two. Disadvantages of the synchronization method

To imagine a situation where one of the methods is that it takes time to calculate the data, but there's a part of it that doesn't need to process the data, but he needs to spend a lot of time, so if we just synchronize this method, the overall code performance will be degraded. And we just have this data part of the synchronization to ensure that the shared data calculation is not a problem, then the code performance is up?

Look at the direct synchronization method:

 Public classSynfunextendsThread {Private intnum=10;//Sharing Data@Override Public voidrun () {Try {             This. Fun ();//calling the synchronization method}Catch(interruptedexception e) {e.printstacktrace (); }    }     Public synchronized voidFun ()throwsinterruptedexception {//use sleep to simulate parts that are complicated but not related to data processing, sleep for three secondsThread.Sleep (3000); System.out.println ("Num before modification is" +num); Num--; System.out.println ("Modified num is" +num); System.out.println ("*************"); }     Public Static voidMain (string[] args) {Synfun synfun=NewSynfun (); Thread T1=NewThread (Synfun); Thread T2=NewThread (Synfun);        T1.start ();    T2.start (); }}

The result: When the result occurs, the first result is waited for three seconds, and the second result occurs after waiting for three seconds.

Improve:

 Public  void throws interruptedexception {        // use sleep to simulate a complex but non-relational part of data processing, sleep three seconds        Thread.Sleep (3000 );         synchronized (this) {            System.out.println ("num before modification" +num);            Num--;            System.out.println ("Modified num is" +num);        }        System.out.println ("*************");    }

is to use a synchronized block of code to synchronize portions of the shared data processing, while the rest of the section lets him cross-run.

The result is the same, but the result is three seconds after the direct appearance of two answers, indicating that the overall performance directly up.

Off-Topic ****************************************************** *****

Java Multi-threaded topic has already published five blog, many seniors (in fact, I am a sophomore student) have given a very good explanation and guidance, here really thank you very much.

1   if (interested in my blog) {2         likes + attention; 3     } Else {4         no else5     }

Deep understanding of the difference between using the synchronized synchronization method and synchronizing code blocks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.