【发布时间】:2010-10-20 15:03:54
【问题描述】:
我有 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();}
}
}
【问题讨论】:
-
为了让事情变得一目了然。在 B.run 类中放入 System.out.println(Thread.currentThread().getId());在 B.pause 中做同样的事情。 K.wait() 实际上是在另一个线程上等待(正如其他人提到的调用者)
-
当你说暂停时,你的意思是立即停止还是完成你正在做的事情然后停下来等我说你可以继续?
标签: java multithreading wait notify