Synchronized usage in Java

Source: Internet
Author: User

1. the synchronized keyword has two scopes:

1) In an object instance, synchronized aMethod () {} can prevent multiple threads from simultaneously accessing the synchronized Method of the object (if an object has multiple synchronized methods, as long as a thread accesses one of the synchronized methods, other threads cannot simultaneously access any of this object's synchronized methods ). At this time, the synchronized methods of different object instances are irrelevant. That is to say, other threads can access the synchronized Method in another object instance of the same class at the same time;

2) is the scope of a class. synchronized static aStaticMethod {} prevents multiple threads from simultaneously accessing the synchronized static method in this class. It can work on all object instances of the class.

2. In addition to using the synchronized keyword before the method, the synchronized keyword can also be used in a block in the method, indicating that only the resources in this block are mutually exclusive. Usage: synchronized (this) {/* block */}. Its scope is the current object;

3. the synchronized keyword cannot be inherited. That is to say, the method of the base class synchronized f () {} is not automatically synchronized f () {} in the inheritance class (){}, instead, it becomes f (){}. You need to explicitly specify a method of the inherited class as the synchronized method;

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.