我在Java中使用Future.get()时遇到了一个奇怪的问题。它总是返回一个InterruptedException,但奇怪的是异常的原因为null,所以我无法确定是谁中断了我。
更糟糕的是,在调用get()之前,我已经检查了Future要执行的任务是否已经完成。
以下是 responsible for the output below 的代码。f 是 Future,callable 返回一个HashMap,其中 Agent 并不是真正相关的内容。如果有太多的 printlines,请见谅,我只是尽可能提供更多信息。callable 的调用方法目前是一个简单的 System.out.println("Hola soy agente"),正如您将看到的,该语句被打印出来,这意味着 callable 也没有引起异常。
以下是代码:
更糟糕的是,在调用get()之前,我已经检查了Future要执行的任务是否已经完成。
以下是 responsible for the output below 的代码。f 是 Future,callable 返回一个HashMap,其中 Agent 并不是真正相关的内容。如果有太多的 printlines,请见谅,我只是尽可能提供更多信息。callable 的调用方法目前是一个简单的 System.out.println("Hola soy agente"),正如您将看到的,该语句被打印出来,这意味着 callable 也没有引起异常。
以下是代码:
try
{
System.out.println(f.isDone()); //true
System.out.println(f.isCancelled()); //false
System.out.println(f.toString()); //FutureTask
newModdedAgents.putAll(f.get());
}catch(InterruptedException e)
{
System.out.println(f.isDone()); //true
System.out.println(f.isCancelled()); //false
System.err.println(e); //It is an interruptedException
System.err.println(e.getCause()); //???? null?
e.printStackTrace();
}
输出结果如下
Hola soy agente
true
false
java.util.concurrent.FutureTask@1c4c94e5
true
false
java.lang.InterruptedException
null
java.lang.InterruptedException
at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1302)
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:248)
at java.util.concurrent.FutureTask.get(FutureTask.java:111)
at com.pf.simulator.Simulation.simulateStep(Simulation.java:217)
at com.pf.gui.ButtonPanel.doWork(ButtonPanel.java:141)
at com.pf.gui.ButtonPanel$1$1.construct(ButtonPanel.java:198)
at com.pf.gui.SwingWorker$2.run(SwingWorker.java:117)
at java.lang.Thread.run(Thread.java:636)
如果您想查看我将可调用对象提交到线程池的位置...那么这就是代码
for(Callable<HashMap<Integer, Agent>> c : agentCallables)
{
Future<HashMap<Integer,Agent>> future = pool.submit(c);
agentFutureSet.add(future);
}
然后我使用迭代器遍历这个Set:
for(Future<HashMap<Integer, Agent>> f : agentFutureSet)
try
{
//Here goes the code at the beginning