我有 3 个线程(A、B、C),我无法让它们按我想要的方式工作。所有这 3 个线程共享对同一个对象的引用 - K。我想做的是启动所有 3 个线程,然后在线程 A 到达某个状态时的某个时间点,暂停线程 B 和 C,直到 A 执行一些方法 work() 并且当工作完成时,恢复 B 和 C。
现在我的代码中有:线程 A 引用了 B 和 C。B 和 C 有一个方法 pause() { synchronized(K) { k.wait; }} 当 A 到达特定状态时,我调用 FROM A 的 run() 方法:B.pause()、C.pause()。现在我期待的是线程 B 和 C 将等待,直到有人发出:k.notifyAll(),但是线程 A 停止了。这在java中正常吗?
代码:
class A implements Runnable {
private K k;
private B b;
private C c;
void run() {
while(something) {
//do something
b.pause();
c.pause();
// !!! here this thread will freeze and doSomething2 wont get executed.
// what i want is to pause B, C, doSomething2 to get executed and then resume B and C
//do something2
synchronized(k) {
k.notifyAll();
}
}
}
}
class B implements Runnable {
private K k;
void run() {
while(something) {
//dome something
}
}
}
public pause() {
synchronized(k) { k.wait();}
}
}
class C implements Runnable {
private K k;
void run() {
while(something) {
//dome something
}
}
}
public pause() {
synchronized(k) { k.wait();}
}
}