ReentrantLock锁的可中断性

此文只是为了记录,先上代码


class BlockedMutex {
    private Lock lock = new ReentrantLock();


    public BlockedMutex() {
        this.lock.lock();// mian线程持有了这个锁
        System.out.println(Thread.currentThread().getName());
    }


    public void f() {
        try {
            this.lock.lockInterruptibly();// 如果当前线程未被中断则获取锁
            System.out.println("lock acquired in f()");
        } catch (InterruptedException e) {
            System.out.println("Interrupted from lock acquisition in f()");
        }
    }
}


class Blocked2 implements Runnable {
    BlockedMutex blocked = new BlockedMutex();


    @Override
    public void run() {
        System.out.println("Waiting for f() in BlockedMutex");
        this.blocked.f();
        System.out.println("Broken out of blocked call");
        System.out.println(Thread.currentThread().getName());
    }


}


public class Interrupting2 {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new Blocked2());
        t.start();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("Issuing t.interrupt()");
        t.interrupt();
    }
}

打印结果:

main
Waiting for f() in BlockedMutex
Issuing t.interrupt()
Interrupted from lock acquisition in f()
Broken out of blocked call
Thread-0

可知, Thread t = new Thread(new Blocked2())中的new Blocked2()的lock被主线程锁持有,且不释放,子线程调用blocked.f()方法而被阻塞,mian线程休眠1s,中断子线程,就产生了以上打印效果,说明了ReentrantLock是可中断的,区别于关键字锁的不可中断性质。


你可能感兴趣的:(Java)