作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在使用 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()
会永远持续。
不明白怎么办
最佳答案
wait()
和 notify()
并不意味着直接使用,而是更好的库用于低级同步的原语。
您应该使用更高级别的并发机制,例如 CountDownLatch
。您可能希望使用值为 4 的 CountDownLatch
。让每个线程调用闩锁的 countDown()
方法,以及您想要等待的线程调用await()。
private CountDownLatch rendezvousPoint = new CountDownLatch(4);
//wait for threads
rendezvousPoint.await();
//do stuff after rendezvous
//in the other 4 threads:
rendezvousPoint.countDown();
关于java - 类似于 Java 中的 Rendez-Vous,但不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8945142/
我在使用 wait() 和 notify() 时遇到了一些问题。我需要有一种约会。 这是一小段代码: class A { private Rdv r; public A(Rdv r)
我是一名优秀的程序员,十分优秀!