Multiple threads: Thread synchronization code block

Source: Internet
Author: User
Tags instance method

Java uses the keyword synchronized for thread synchronization with four sync blocks:

1. Example method

2. Static method

3. Synchronization blocks in the instance method

4. Synchronous block in static method

Instance method synchronization: Use the Synchronized keyword in the method declaration to synchronize on the object that owns the method

1   Public synchronized void Increase () {2          this. id++;    3  }

Static method synchronization: As with instance method synchronization, use the Synchronized keyword in the method declaration to synchronize on the class object that owns the method, while allowing only one thread to execute a static synchronization method in the same class

1  Public Static  synchronized void Increase () {2           this. id++;    3 }

Synchronization blocks in instance methods: Do not use the Synchronized keyword in the method declaration, but use synchronized to enclose part of the code in the method to synchronize

1   Public void Increase () {2         synchronized (this) {3            this. id++;    4         }5  }

Synchronous blocks in static methods: Similar to static method synchronization, do not use the Synchronized keyword in the method declaration, use synchronized to surround part of the code in the method, synchronize

1   Public Static void Increase () {2          synchronized (this) {3             this. id++;    4          }5   }

Multiple threads: Thread synchronization code block

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.