什么是可中断锁

Lock是可中断锁,而synchronized不是可中断锁。现假设线程A和B都要获取对象O的锁定,假设A获取了对象O锁,B将等待A释放对O的锁定,如果使用synchronized,如果A不释放,B将一直等下去,不能被中断;如果使用ReentrantLock,如果A不释放,可以使B在等待了足够长的时间以后,中断等待,而干别的事情。获取锁超时机制还是属于不可中断,属于超时被动放弃去竞争锁,而lockInterruptibly是可主动放弃竞争锁行为的一种方式。

Lock接口的线程获取锁的三种方式

1、lock(),如果获取了锁立即返回,如果别的线程持有锁,当前线程则一直处于休眠状态,直到获取锁;

2、tryLock(),如果获取了锁立即返回true,如果别的线程正持有锁,立即返回false;

3、tryLock(long timeout,TimeUnit unit),如果获取了锁定立即返回true,如果别的线程正持有锁,会等待参数给定的时间,在等待的过程中,如果获取了锁定,就返回true,如果等待超时,返回false;

lockInterruptibly()方法

先说说线程的打扰机制,每个线程都有一个打扰标志。这里分两种情况:

  • 线程在sleep或wait、join,此时如果别的进程调用此进程的interrupt()方法,此线程会被唤醒并被要求处理InterruptedException;(Thread在做IO操作时也可能有类似行为)
  • 此线程在运行中,则不会收到提醒。但是此线程的 打扰标志会被设置,可以通过isInterrupted()查看并作出处理。

lockInterruptibly()和上面的第一种情况是一样的, 线程在请求lock并被阻塞时,如果被interrupt,则此线程会被唤醒并被要求处理InterruptedException。lock()的代码演示:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo {
    public static void main(String[] args) throws InterruptedException {
        final Lock lock = new ReentrantLock();
        lock.lock();
        Thread.sleep(1000);
        Thread t1 = new Thread(() -> {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + " interrupted.");
        });
        t1.start();
        Thread.sleep(1000);
        //试图将t1中断执行,但并不能中断t1
        t1.interrupt();
        Thread.sleep(2000);
    }
}

lockInterruptibly()代码演示:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo {
    public static void main(String[] args) throws InterruptedException {
        final Lock lock = new ReentrantLock();
        lock.lock();
        Thread.sleep(1000);
        Thread t1 = new Thread(() -> {
            try {
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName() + " interrupted.");
            }
        });
        t1.start();
        Thread.sleep(1000);
        //试图将t1中断执行,是可以的,产生了一个InterruptedException异常
        t1.interrupt();
        Thread.sleep(1000);
    }
}

lockInterruptibly()源码说明:线程被唤醒后检测到中断请求,则立即抛出中断异常(由上层调用者来处理这个异常),该操作导致方法结束。下面是源码:lockInterruptibly() -> sync.acquireInterruptibly(1) -> doAcquireInterruptibly():

/**
 * Acquires in exclusive interruptible mode.
 * @param arg the acquire argument
 */
private void doAcquireInterruptibly(int arg)
	throws InterruptedException {
	final Node node = addWaiter(Node.EXCLUSIVE);
	boolean failed = true;
	try {
		for (;;) {
			final Node p = node.predecessor();
			if (p == head && tryAcquire(arg)) {
				setHead(node);
				p.next = null; // help GC
				failed = false;
				return;
			}
			if (shouldParkAfterFailedAcquire(p, node) &&
				parkAndCheckInterrupt())
				throw new InterruptedException();
		}
	} finally {
		if (failed)
			cancelAcquire(node);
	}
}

下面是lock()的源码:lock() -> sync.lock() -> acquire(1) -> acquireQueued():

/**
 * Acquires in exclusive uninterruptible mode for thread already in
 * queue. Used by condition wait methods as well as acquire.
 *
 * @param node the node
 * @param arg the acquire argument
 * @return {@code true} if interrupted while waiting
 */
final boolean acquireQueued(final Node node, int arg) {
	boolean failed = true;
	try {
		boolean interrupted = false;
		for (;;) {
			final Node p = node.predecessor();
			if (p == head && tryAcquire(arg)) {
				setHead(node);
				p.next = null; // help GC
				failed = false;
				return interrupted;
			}
			if (shouldParkAfterFailedAcquire(p, node) &&
				parkAndCheckInterrupt())
				interrupted = true;
		}
	} finally {
		if (failed)
			cancelAcquire(node);
	}
}

可中断锁与非中断锁结论

ReentrantLock的中断和非中断加锁模式的区别在于:线程尝试获取锁操作失败后,在等待过程中,如果该线程被其他线程中断了,它是如何响应中断请求的。lock方法会忽略中断请求,继续获取锁直到成功;而lockInterruptibly则直接抛出中断异常来立即响应中断,由上层调用者处理中断。