ReentrantLock.lockInterruptibly()方法 Demo

1,304 阅读1分钟
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest {
    public static ReentrantLock reenT = new ReentrantLock();//参数默认false,不公平锁
    private static void test3() {
        Thread t0 = new Thread(() -> {
            try {
                reenT.lockInterruptibly();
                System.out.println(Thread.currentThread().getName() + " 获得了锁");
                Thread.sleep(2000L);
                reenT.unlock();
                System.out.println(Thread.currentThread().getName() + " 释放了锁");
            } catch (InterruptedException e) {
                reenT.unlock();
                System.out.println(Thread.currentThread().getName() + " 被中断,释放锁");
                e.printStackTrace();
            }
        });
        Thread t1 = new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + " 开始执行");
                reenT.lock();
                System.out.println(Thread.currentThread().getName() + " 获得了锁");
                Thread.sleep(2000L);
                reenT.unlock();
                System.out.println(Thread.currentThread().getName() + " 释放了锁");
            } catch (Exception e) {
                System.out.println(Thread.currentThread().getName() + " 被中断");
                e.printStackTrace();
            }
        });

        try {
            t0.start();
            Thread.sleep(200L);
            t0.interrupt();
            t1.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        try {
            test3();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
> 
Thread-0 获得了锁
Thread-0 被中断,释放锁
Thread-1 开始执行
Thread-1 获得了锁
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at ReentrantLockTest.lambda$test3$6(ReentrantLockTest.java:147)
	at java.lang.Thread.run(Thread.java:748)
Thread-1 释放了锁

t1被中断以后,弹出InterruptedException异常,此时并没有立刻释放锁,在异常处理中,我们手动释放了锁。因此t1才有可能获得锁。