【发布时间】:2015-12-12 03:59:56
【问题描述】:
我想对函数进行异步调用并返回而不等待结果(在 Java 中)。我为此编写的代码是:
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(new Callable<Void>()
{
public Void call() throws Exception, TimeoutException {
hostNetworkSystem.updatePortGroup("Management Network", spec);
return null;
}
});
我已经尝试过 Runnable 和 Callable,但是当我在 Eclipse 中通过代码进行调试时,线程卡在 call() 函数并没有在提交任务后立即返回。
我错过了什么吗?
卡在:
hostNetworkSystem.updatePortGroup("Management Network", spec);
准确地说。我可以看到结果,执行该操作,但它不会从这里返回。
为了更好地理解,整个调用如下所示:
public void main()
{
try {
AsyncCall asyncCalls = new AsyncCall();
List<PortGroupData> portData = asyncCalls.updatePortGroupFuture(hostNetworkSystem, portGroupName,
portGroupData, modelType, oobmStatus, vlanID);
return portData;
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("InterruptedException " + e.getMessage().toString());
} catch (ExecutionException e) {
System.out.println("ExecutionException " + e.getMessage().toString());
e.printStackTrace();
} catch (Exception e) {
System.out.println("Exception " + e.getMessage().toString());
e.printStackTrace();
}
}
public void updatePortGroupFuture(final HostNetworkSystem hostNetworkSystem,
final String portGroupName, final NetworkParameters networkData, final String modelType,
final boolean oobmStatus, int vlanID) throws InterruptedException, ExecutionException, Exception
{
<some other actions>
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(new Callable<Void>()
{
public Void call() throws Exception, TimeoutException {
hostNetworkSystem.updatePortGroup("Management Network", spec);
return null;
}
});
return;
}
【问题讨论】:
-
卡在
call或submit?你在某个地方设置了断点吗?您是否尝试过在您的可调用对象中放置一些日志语句,以查看在您运行(而不是调试)应用程序时它是否被调用?
标签: java executorservice futuretask