我在Java中使用Future.get()有一个WEIRD问题。它总是返回一个InterruptedException,但是很奇怪的是,异常的原因为null,所以我不能说是谁打断了我。
更糟糕的是,因为我在调用get()之前进行了检查,而Future要做的工作已经完成。
这是负责以下输出的代码。 f是Future的,并且可调用函数返回一个HashMap,其中Agent并不真正相关。很抱歉,如果打印行太多,我只是想提供尽可能多的信息。现在,来自callable的call方法是一个简单的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);
}
然后我用
for(Future<HashMap<Integer, Agent>> f : agentFutureSet)
try
{
//Here goes the code at the beginning
最佳答案
在调用get()
之前,您是否检查了线程的中断标志?您可以使用Thread.currentThread().isInterrupted()
做到这一点。
有关更多信息,请查看Future.get()的javadoc,以了解为什么会引发InterruptedException。
关于java - Future.get()总是被InterruptedException中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4268457/