类似于 Java 中的 Rendez-Vous,但不起作用
我在使用 wait()
和 notify()
时遇到了一些麻烦。我需要有一种约会。
事情是这样的,在一小段代码中:
class A {
private Rdv r;
public A(Rdv r) {
this.r = r;
}
public void someMethod() {
synchronized(r) {
r.wait();
}
// ***** some stuff never reached*****
}
}
class Rdv {
private int added;
private int limit;
public Rdv(int limit) {
this.added = 0;
this.limit = limit;
}
public void add() {
this.added++;
if(this.added == this.limit) {
synchronized(this) {
this.notifyAll();
}
}
}
}
class Main {
public static void main(String[] args) {
Rdv rdv = new Rdv(4);
new Runnable() {
public void run() {
A a = new A(rdv);
a.someMethod();
}
}.run();
rdv.add();
rdv.add();
rdv.add();
rdv.add();
}
}
这个想法是等到 4 个线程告诉“嘿,我完成了”,然后再运行 someMethod()
的末尾。 但是,尽管有 notifyAll()
,但 wait()
会永远持续下去。
我不明白怎么办
I have some troubles using wait()
and notify()
. I need to have a kind of rendez-vous.
Here is the thing, in a small piece of code:
class A {
private Rdv r;
public A(Rdv r) {
this.r = r;
}
public void someMethod() {
synchronized(r) {
r.wait();
}
// ***** some stuff never reached*****
}
}
class Rdv {
private int added;
private int limit;
public Rdv(int limit) {
this.added = 0;
this.limit = limit;
}
public void add() {
this.added++;
if(this.added == this.limit) {
synchronized(this) {
this.notifyAll();
}
}
}
}
class Main {
public static void main(String[] args) {
Rdv rdv = new Rdv(4);
new Runnable() {
public void run() {
A a = new A(rdv);
a.someMethod();
}
}.run();
rdv.add();
rdv.add();
rdv.add();
rdv.add();
}
}
The idea is to wait until 4 threads tell "hey, i'm done" before to run the end of someMethod()
.
But the wait()
lasts forever, despite of the notifyAll()
.
I don't get how
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
wait()
和notify()
并不意味着直接使用,而是更好的库用于低级同步的原语。您应该使用更高级别的并发机制,例如
CountDownLatch
。您可能希望使用值为 4 的CountDownLatch
。让每个线程调用闩锁的countDown()
方法,以及您想要等待的线程调用await()。wait()
andnotify()
are not meant to be used directly but rather are primitives that better libraries use for low-level synchronization.You should use a higher-level concurrency mechanism, such as
CountDownLatch
. You would want to use aCountDownLatch
with a value of 4. Have each of the threads call thecountDown()
method of the latch, and the one you want to wait to callawait()
.嗯...我是唯一一个注意到您实际上没有启动任何线程的人吗?
应该是
,如果你想让 4 个线程等待,则应该执行 4 次。
Um... am I the only one noticing that you are not actually starting any threads?
should be
And this should be executed 4 times if you want to have 4 threads waiting.
不要自己搞乱
wait()
和notify()
,而是考虑使用CountDownLatch
Instead of messing with
wait()
andnotify()
yourself, consider using aCountDownLatch
当然达不到,因为A类的每个实例都有一个Rdv类的不同实例;
您需要在 A 类中使用 RDV 作为静态变量
Of course it won't be reached, because every instance of class A has a different instance of class Rdv;
You need to use RDV as a static variable in class A