如何使用ReentrantLock锁定? [英] How to lock with ReentrantLock?

查看:91
本文介绍了如何使用ReentrantLock锁定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望以下测试只打印已被锁定一次。
然后它会打印该行。

I would expect the following test to only print "has been locked" once. BUT it consequently prints the line.

public class LocKTest {
    @Test
    public void testLock() {
        Lock lock = new ReentrantLock();
        while (true) {
            if (lock.tryLock()) {
                //lock.lock(); same result if I include an explicit lock here
                System.out.println("has been locked");
            }
        }
    }
}

As据我所知, tryLock 将锁定 ReentrantLock 如果可能(即如果尚未锁定)。但显然事实并非如此。

As far as I understood, tryLock will lock the ReentrantLock if possible (ie if not locked yet). But obviously this is not the case.

如何设置这样的锁线程安全?

How can I set such a lock threadsafe?

推荐答案

名称是 ReentrantLock ,这意味着如果你已经拥有锁,你可以重新输入

The name is ReentrantLock, meaning you can re-enter if you already own the lock.

如果你想拥有线程块,你可以使用例如信号量 1(或更多) )许可证。

If you wish to have the thread block, you could use for example a Semaphore with 1 (or more) permits.

这篇关于如何使用ReentrantLock锁定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆