Java 中一个线程可以同时调用两个锁的 wait() (6)
我刚刚在 Java 中搞乱了线程,以了解它们(这似乎是最好的方法),现在了解了 Synchronize、wait() 和 notification() 发生了什么。
我很好奇是否有办法同时 wait() 两个资源。我认为以下内容并不能完全实现我的想法(编辑:请注意,通常的 while 循环已被排除在本示例之外,只专注于释放两个资源< /em>):
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 返回。目标是释放 token1 和 token2,然后在两者都可用时恢复(请注意,将 token1.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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,不使用标准 Java 锁。虽然我猜你可以建造这样的锁。
wait
应该在while
循环内调用(wait
可能会虚假唤醒,并且在大多数情况下您无论如何都需要循环)。所以某种标志会更有意义。No, not with a standaad Java lock. Although I guess you could construct such a lock.
wait
should be called within awhile
loop (wait
may spuriously wakeup, and in most situations you would want the loop anyway). So some kind of flag would make more sense.该示例不包括执行等待的条件。通常,等待只会发生,直到满足条件。一般来说,我认为可以通过单个锁定/等待并将“token1 和 token2”抽象到条件逻辑中来完成您想要的任务。
例如
The example doesn't include the condition upon which the waiting will be performed. Typically, waiting will occur only and until the condition has been met. Generally, I would think that one could accomplish what you are trying to by having a single lock / wait and abstracting the 'token1 and token2' into the conditional logic.
For example