Differences between Synchronized Method and synchronized static method

Source: Internet
Author: User
Tags class generator

The explanation in the book is very simple and clear, but it may be a little difficult to use.

The synchronization object of synchronized method refers to the class instance object,

The synchronization object of synchronized static method refers to the class itself, that is, all objects share the synchronization object.

 

The problem lies in

Public int kk (){

G ();

}

Which object is used when G () is called in KK? Yes. The instance object is used! Whether you use g () or even. G (), the instance object takes precedence.

To use a class object, you must call even. G () outside the even class ()

 

 

Class generator {

Private Static int even = 0;

 

Random r = new random (1000 );

 

Generator (){

 

}

 

Public synchronized int F (){

Even ++;

 

 

 

Even ++;

 

Return even;

}

 

Public synchronized static int g (){

Even ++;

Try {

Thread. Sleep (10 );

} Catch (interruptedexception e ){

// Todo auto-generated Catch Block

E. printstacktrace ();

}

Even ++;

 

Return even;

}

Public int kk (){

G ();

}

}

 

 

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.