dea*_*iop 2 java concurrency multithreading notify wait
我有一些麻烦使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
我们的想法是等到4个线程告诉"嘿,我已经完成"然后再运行结束someMethod().但是wait(),尽管如此,这种情况永远持续下去notifyAll().
我不知道如何
wait()而notify()并不意味着可以直接使用,而是是更好的库使用低级别的同步原语.
您应该使用更高级别的并发机制,例如CountDownLatch.您可能希望使用CountDownLatch值为4.让每个线程调用countDown()锁存器的方法,以及您要等待调用的方法await().
private CountDownLatch rendezvousPoint = new CountDownLatch(4);
//wait for threads
rendezvousPoint.await();
//do stuff after rendezvous
//in the other 4 threads:
rendezvousPoint.countDown();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1612 次 |
| 最近记录: |