← 中文资源

简体中文版本

ReentrantLock.tryLock 有界等待

ReentrantLock.tryLock(timeout) 给锁等待加上限:持有者及时释放就能等到锁,长期占用则按超时放弃而不是无限阻塞,只有拿到锁才需要 unlock。

阅读英文原文

实现说明

ReentrantLock.tryLock 有界等待的核心是类 BoundedLockWait。

使用要点

  • 演示输出是带标签的(acquired after release:、gave up instead of waiting:),每个操作都会留下自己的一行标注。

常见问题

运行「ReentrantLock.tryLock 有界等待」会打印什么?

整个文件跑完,输出行以 acquired after release:、gave up instead of waiting: 这类前缀开头。

核心语句

Thread holder = Thread.ofPlatform().start(() -> {
    LOCK.lock();
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } finally {
        LOCK.unlock();
    }
});
Thread greedy = Thread.ofPlatform().start(() -> {
    LOCK.lock();
    try {
        Thread.sleep(300);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } finally {
        LOCK.unlock();
    }
});
Thread.sleep(20);

代码示例

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

public class BoundedLockWait {

    static final ReentrantLock LOCK = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        // 持有者 100ms 后释放:tryLock(1s) 在限期内等到锁
        Thread holder = Thread.ofPlatform().start(() -> {
            LOCK.lock();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                LOCK.unlock();
            }
        });

        Thread.sleep(20);
        boolean got = LOCK.tryLock(1, TimeUnit.SECONDS);
        System.out.println("acquired after release: " + got);
        if (got) {
            LOCK.unlock();
        }
        holder.join();

        // 长期占用时:tryLock(50ms) 到期放弃,而不是无限等待
        Thread greedy = Thread.ofPlatform().start(() -> {
            LOCK.lock();
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                LOCK.unlock();
            }
        });

        Thread.sleep(20);
        boolean gave = LOCK.tryLock(50, TimeUnit.MILLISECONDS);
        System.out.println("gave up instead of waiting: " + !gave);
        if (gave) {
            LOCK.unlock();
        }
        greedy.join();
    }
}