Notes for getting and releasing reentrant locks

Source: Internet
Author: User

What Is A reentrant lock? The literal meaning of "re-entry" is already obvious, that is, you can re-enter. Reentrant locks, that is, a thread is

After obtaining a lock, you can continue to obtain the lock, that isAllows a thread to obtain the same lock multiple times.. For example, synchronized built-in locks can be reentrant.

If Class A has two synchornized Methods: Method1 and method2, calling Method1 is allowed. Apparently re-import locks to the programming tape

Great convenience. If the built-in lock is not reentrant, the problem is that the synchornized method of one class cannot call other

The synchornized method cannot call the synchornized method in the parent class. The display lock reentrantlock provided by JDK is also applicable to built-in locks.

Here we mainly talk about the things needed to release the reentrant lock.

public static void main(String[] args) throws Exception{    final ReentrantLock lock = new ReentrantLock();    Thread t = new Thread(new Runnable()    {        @Override        public void run()        {            lock.lock();            System.out.println("execute");            lock.unlock();        }    });    lock.lock();    lock.lock();    t.start();    Thread.sleep(200);    System.out.println("realse one once");    lock.unlock();}

The above code will have a deadlock because the main thread acquires the lock twice, but only releases the lock once, causing the thread t to never get the lock.One thread obtains

FetchHow many locks must be released. This is also applicable to built-in locks. Each time you enter and exit the synchornized method (code block), it is

A complete lock acquisition and release.

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.