The object lock distinction of Java multithreading synchronization

Source: Internet
Author: User

Multi-Threaded synchronization: Multiple threads work together to perform tasks correctly.

We often see the multithread synchronization keyword synchronized, then it is the use of Who do sync lock.

To achieve multithreaded synchronization, you must ensure that the sync lock is shared only.

Synchronized is typically used in 3 scenarios:

1. Non-static methods

2. Static method

3. Code block


First, non-static methods

A synchronization lock is an instance of the object in which the current method resides, and if the object is a singleton, thread synchronization can be implemented.

Public synchronized void Run () {for
            (int start =1; start < start++) {
                System.out.println ("No." + Threadno + ":" + start);
            }
        

Second, static method

Synchronous locks are the classes in which the current method is located, and the class is unique, so it is certain that thread synchronization can be implemented.

public static synchronized void Test () {
        System.out.println ("test");
    }

Three, code block

Synchronization locks can be customized, but are guaranteed to be unique.

public void Run () {synchronized (.) {for
                (int start = 1; start < start++) {
                    System.out.println ("No . "+ Threadno +": "+ Start";}}}
        
Here, this is the instance of the class in which the current method is located, and if it is a single case, it is unique.

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.