什么是可中断锁
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()的代码演示:
1import java.util.concurrent.locks.Lock;
2import java.util.concurrent.locks.ReentrantLock;
3
4public class ReentrantLockDemo {
5 public static void main(String[] args) throws InterruptedException {
6 final Lock lock = new ReentrantLock();
7 lock.lock();
8 Thread.sleep(1000);
9 Thread t1 = new Thread(() -> {
10 lock.lock();
11 System.out.println(Thread.currentThread().getName() + " interrupted.");
12 });
13 t1.start();
14 Thread.sleep(1000);
15 //试图将t1中断执行,但并不能中断t1
16 t1.interrupt();
17 Thread.sleep(2000);
18 }
19}
lockInterruptibly()代码演示:
1import java.util.concurrent.locks.Lock;
2import java.util.concurrent.locks.ReentrantLock;
3
4public class ReentrantLockDemo {
5 public static void main(String[] args) throws InterruptedException {
6 final Lock lock = new ReentrantLock();
7 lock.lock();
8 Thread.sleep(1000);
9 Thread t1 = new Thread(() -> {
10 try {
11 lock.lockInterruptibly();
12 } catch (InterruptedException e) {
13 System.out.println(Thread.currentThread().getName() + " interrupted.");
14 }
15 });
16 t1.start();
17 Thread.sleep(1000);
18 //试图将t1中断执行,是可以的,产生了一个InterruptedException异常
19 t1.interrupt();
20 Thread.sleep(1000);
21 }
22}
lockInterruptibly()源码说明:线程被唤醒后检测到中断请求,则立即抛出中断异常(由上层调用者来处理这个异常),该操作导致方法结束。下面是源码:lockInterruptibly() -> sync.acquireInterruptibly(1) -> doAcquireInterruptibly():
1/**
2 * Acquires in exclusive interruptible mode.
3 * @param arg the acquire argument
4 */
5private void doAcquireInterruptibly(int arg)
6 throws InterruptedException {
7 final Node node = addWaiter(Node.EXCLUSIVE);
8 boolean failed = true;
9 try {
10 for (;;) {
11 final Node p = node.predecessor();
12 if (p == head && tryAcquire(arg)) {
13 setHead(node);
14 p.next = null; // help GC
15 failed = false;
16 return;
17 }
18 if (shouldParkAfterFailedAcquire(p, node) &&
19 parkAndCheckInterrupt())
20 throw new InterruptedException();
21 }
22 } finally {
23 if (failed)
24 cancelAcquire(node);
25 }
26}
下面是lock()的源码:lock() -> sync.lock() -> acquire(1) -> acquireQueued():
1/**
2 * Acquires in exclusive uninterruptible mode for thread already in
3 * queue. Used by condition wait methods as well as acquire.
4 *
5 * @param node the node
6 * @param arg the acquire argument
7 * @return {@code true} if interrupted while waiting
8 */
9final boolean acquireQueued(final Node node, int arg) {
10 boolean failed = true;
11 try {
12 boolean interrupted = false;
13 for (;;) {
14 final Node p = node.predecessor();
15 if (p == head && tryAcquire(arg)) {
16 setHead(node);
17 p.next = null; // help GC
18 failed = false;
19 return interrupted;
20 }
21 if (shouldParkAfterFailedAcquire(p, node) &&
22 parkAndCheckInterrupt())
23 interrupted = true;
24 }
25 } finally {
26 if (failed)
27 cancelAcquire(node);
28 }
29}
可中断锁与非中断锁结论
ReentrantLock的中断和非中断加锁模式的区别在于:线程尝试获取锁操作失败后,在等待过程中,如果该线程被其他线程中断了,它是如何响应中断请求的。lock方法会忽略中断请求,继续获取锁直到成功;而lockInterruptibly则直接抛出中断异常来立即响应中断,由上层调用者处理中断。