我正在尝试保存一个静态的期货列表,并在稍后取消()或通知()正在进行的期货。与这些 Futures 相关联的 Callable 类在其中有一个 wait() ,因此必须由外部源通知每个类以继续。但是,我对 notify() 的调用似乎被忽略了,因为可调用对象永远不会超过它们的等待语句。具有 Futures 列表的类看起来像这样:
private static Map <String, Future<Object>> results = new HashMap <String, Future<Object>>();
ExecutorService taskExecutor;
public void doStuff() {
taskExecutor = Executors.newCachedThreadPool();
// loop inifinitely - external processes will modify the conditions within
while(!shutItDown) {
if (<condition1>) {
// condition 1 dictates the kick-off of a new callable
Future<Object> future = taskExecutor.submit(new MyCallable(id));
results.put(id, future);
}
else if (<condition2>) {
// condition 2 represents a callable in a wait status needs
// to be notified
Future<Object> future = results.get(uid);
if (future != null) {
synchronized(future) {
future.notify(); // this doesn't have the desired effect!
}
}
}
}
}
Callable 类现在只是一个模型,看起来类似于:
public class MyCallable implements Callable<Object> {
private String id;
public MyCallable(String id) {
this.id = id;
}
@Override
public Object call() throws Exception {
try {
// do some work here, then wait on outside notification
synchronized(this) {
this.wait(); // never gets past here!!!
}
// do some other work here, once this has been notified
}
catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
调用了 notify() 方法,但似乎没有效果。Future 的对象引用似乎是有效的(即局部变量“future”与存储在静态列表中的 future 的引用相匹配)。
我可能在这里遗漏了一些基本的并发概念,但我预计当满足条件 2 时,我的 Callable 将继续通过 wait() 调用。
请注意,如果我使用 cancel() 而不是 notify(),它会中断我的 runnable 并导致如我所料的 InterruptedException。