Java's Synchronized

Source: Internet
Author: User

Java's Synchronized
    • When the task is to execute the Syschronized method, this object is locked, and the other synchronized methods on that object will only be called until the previous method call is complete and the lock is freed.

      class  Demo{    synchronized void a();    syschronized void b();}如果a被调用并且没有被释放,此时调用b,是不能执行的,只有等待a执行完,才可以被调用

For a particular object, all of its synchronized methods share a lock, which can be used to prevent multiple tasks from accessing the encoded object memory at the same time.

    • If you synchronize with this in a method block, the effect of the critical section is reduced directly to the range of synchronization

      class  Demo{    Object o ;    public Demo(){        o = this;    }    synchronized void a(){    }    void b(){        synchronized(o){        }    }

      }

Summarize:

    1. When two concurrent threads access the same object in the synchronized (this) synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block.
    2. However, when a thread accesses one synchronized (this) of object to synchronize a block of code, another thread can still access the non-synchronized (this) synchronous code block in that object.
    3. In particular, when a thread accesses one of the synchronized (this) synchronization blocks of object, the access of other threads to all other synchronized (this) synchronization blocks in object is blocked.
    4. The third example also applies to other synchronous code blocks. That is, when a thread accesses a synchronized (this) of object to synchronize a block of code, it obtains the object lock of the objects. As a result, other threads are temporarily blocking access to all of the synchronization code portions of the object.
    5. The above rules also apply to other object locks.

For more details:

Java's Synchronized

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.