线程可以在Java中一次在两个锁上调用wait()吗? [英] Can a thread call wait() on two locks at once in Java (6)

查看:136
本文介绍了线程可以在Java中一次在两个锁上调用wait()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在弄乱Java中的线程来处理它们(这似乎是最好的方法),现在了解了sync,wait()和notify()的情况.

我很好奇是否有一种方法可以同时对两个资源进行wait().我认为以下内容并不能完全满足我的想法( edit :请注意,此示例中省去了通常的while循环,只专注于释放两个资源):

synchronized(token1) {
    synchronized(token2) {
        token1.wait();
        token2.wait(); //won't run until token1 is returned
        System.out.println("I got both tokens back");
    }
}

在这种(非常人为)的情况下,将保留token2直到返回token1,然后将保留token1直到返回token2.目标是释放令牌1和令牌2,然后在它们都可用时恢复(请注意,将令牌1.wait()移到内部同步循环之外并不是我想要的).

循环检查两者是否可用可能更适合于实现此行为(这是否接近双重检查锁定的想法?),但会占用额外的资源-我不寻求明确的解决方案,因为这只是为了满足我的好奇心.

编辑为了便于讨论,我们要说的是,这里的两个标记表示线程必须同时使用的两个不同资源,而其他一些线程将同时需要两个资源.

解决方案

否,不是带有标准的Java锁.虽然我猜您可以构造这样的锁.

wait应该在while循环中调用(wait可能会虚假地唤醒,并且在大多数情况下,您还是希望循环).因此,某种标记会更有意义.

I've just been messing around with threads in Java to get my head around them (it seems like the best way to do so) and now understand what's going on with synchronize, wait() and notify().

I'm curious about whether there's a way to wait() on two resources at once. I think the following won't quite do what I'm thinking of (edit: note that the usual while loops have been left out of this example to focus just on freeing up two resources):

synchronized(token1) {
    synchronized(token2) {
        token1.wait();
        token2.wait(); //won't run until token1 is returned
        System.out.println("I got both tokens back");
    }
}

In this (very contrived) case token2 will be held until token1 is returned, then token1 will be held until token2 is returned. The goal is to release both token1 and token2, then resume when both are available (note that moving the token1.wait() outside the inner synchronized loop is not what I'm getting at).

A loop checking whether both are available might be more appropriate to achieve this behaviour (would this be getting near the idea of double-check locking?), but would use up extra resources - I'm not after a definitive solution since this is just to satisfy my curiosity.

Edit Let's just for the sake of argument say that the two tokens here represent two distinct resources that the thread must use at the same time, and that some other threads will need both at the same time.

解决方案

No, not with a standaad Java lock. Although I guess you could construct such a lock.

wait should be called within a while loop (wait may spuriously wakeup, and in most situations you would want the loop anyway). So some kind of flag would make more sense.

这篇关于线程可以在Java中一次在两个锁上调用wait()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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