The difference between the lock and lockinterruptibly methods of the Java.util.concurrent.locks.Lock class __lock and Lockinterruptib

Source: Internet
Author: User

What is an interruptible lock fetch? Is whether the thread is able to respond to interrupts while waiting to acquire a lock so that it can be unblocked when interrupted

Plug state, and not innocently have been waiting. The built-in lock (synchronized) of a Java object is an interruptible lock, which means that if a line

A thread waits for a built-in lock on an object, even if the thread is interrupted by another thread, and it continues to wait for the built-in lock instead of unblocking

State, nor will it throw interruptedexception. The Lock class Lock () is similar to synchronized, and is not interrupted while waiting for the lock to be acquired,

Does not respond to interrupt requests; The lockinterruptibly is interruptible, and the thread is able to respond to interrupts and throw exceptions while waiting for the lock to be acquired.

public static void Testlock () throws Exception
{
    final lock lock = new Reentrantlock ();

    thread T1 = new Thread (new Runnable ()
    {
        @Override public
        Void Run ()
        {
            //1. Test lock
            //Lock.lock ( );

            2. Test lockinterruptibly
            try
            {
                lock.lockinterruptibly ();
            }
            catch (interruptedexception e)
            {
                System.out.println ("interrupted.");}}
    );

    When the lock is occupied, let the T1 start to run
    Lock.lock ();
    T1.start ();

    Thread.Sleep (m);
    T1.interrupt ();
}

You can test the code at 1 and 2, respectively. The call to Lock.lock () found that the thread T1 never ended, that T1 had been waiting to acquire the lock, and called lock.

Lockinterruptibly () finds that the T1 thread can terminate and print interrupted, which responds to a thread interrupt request.

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.