Java Thread Sync __java

Source: Internet
Author: User
Thread synchronization mechanism

Synchronization mechanisms are provided in Java to effectively prevent resource conflicts. The synchronization mechanism uses the Synchronized keyword. 1. Sync Block

The synchronization block is called a critical section, which is established using the Synchronized keyword, and its syntax is as follows:

Synchronized (Object) {
}

The operations of a shared resource are typically placed within a synchronized defined area so that when other threads acquire the lock, they must wait for the lock to be released before they can enter the zone. object is any object, each object has a flag bit, and has two values, 0 and 1, respectively. When a thread runs to a synchronization block, it first checks the flag bit of the object, or 0 states, indicating that another thread is running in the synchronization block. This is the thread in the ready state, knowing that the thread in the synchronization block finishes the code in the synchronization block. When the identity bit of the object is set to 1, the thread cannot execute the code in the synchronization block and set the identity bit of the object to 0 to prevent other threads from executing the code in the synchronization block. 2. Sync Method

The synchronization method is the method that modifies the Synchronized keyword before the method, and its syntax is as follows:

synchronized void F () {
}

When an object invokes a synchronization method, the other synchronization methods on that object must wait for the synchronization method to complete before it can be executed.

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.