← 中文资源

简体中文版本

ReentrantLock 可中断等锁

lockInterruptibly 在等锁期间可被中断取消,普通 lock() 的等待打不断;捕获后要恢复中断标记,避免长临界区把线程永久堵死。

阅读英文原文

实现说明

底层就是类 InterruptibleLock。

使用要点

  • 直接运行文件,输出会带上标签,比如 waiter got the lock、waiter cancelled while waiting、done——输出的每一行都能指回产生它的那次调用。

常见问题

运行「ReentrantLock 可中断等锁」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 waiter got the lock、waiter cancelled while waiting、done 这类标签。

核心语句

Thread holder = Thread.ofPlatform().name("holder").start(() -> {
    gate.lock();
    try {
        Thread.sleep(300); // 长临界区:等待者被堵在队列里
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } finally {
        gate.unlock();
    }
});
Thread.sleep(100); // waiter 此刻正阻塞在 lockInterruptibly 上
waiter.interrupt();
Thread.currentThread().interrupt(); // 恢复中断标记
System.out.println("waiter cancelled while waiting");

代码示例

import java.util.concurrent.locks.ReentrantLock;

public class InterruptibleLock {

    private static final ReentrantLock gate = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread holder = Thread.ofPlatform().name("holder").start(() -> {
            gate.lock();
            try {
                Thread.sleep(300); // 长临界区:等待者被堵在队列里
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                gate.unlock();
            }
        });

        Thread.sleep(50); // holder 先拿到锁,waiter 进队等待
        Thread waiter = Thread.ofPlatform().name("waiter").start(() -> {
            try {
                // lockInterruptibly cancels waiting when interrupted
                gate.lockInterruptibly();
                try {
                    System.out.println("waiter got the lock");
                } finally {
                    gate.unlock();
                }
            } catch (InterruptedException cancelled) {
                Thread.currentThread().interrupt(); // 恢复中断标记
                System.out.println("waiter cancelled while waiting");
            }
        });

        Thread.sleep(100); // waiter 此刻正阻塞在 lockInterruptibly 上
        waiter.interrupt();
        waiter.join();
        holder.join();
        System.out.println("done");
    }
}