gpt4 book ai didi

java - executor.shutDownNow() 不会停止执行内部方法

转载 作者:行者123 更新时间:2023-11-29 10:04:36 25 4
gpt4 key购买 nike

我创建了一个 future 任务并将其提交给 Executor。在 run() 方法中,我创建了一个 placementPlanner 对象。此类中的方法调用其他类。但是,当我调用 executor.shutDownNow() 时,调用的内部方法不会停止执行。如何调用我杀死所有子线程并停止调用方法。代码如下。

static List<Result> invokePlacementPlannerWithTimeout(int timeoutSecs,
final String requestType, final RequestMap requestMap,
final ReleaseMap releaseMap, final SysConfig systemConfig,
final Request request, final SigmaBlade hostData,
final ServiceLevelData serviceLevelData,
final List<Service> serviceList, final String transactionID) throws IOException {

/**
* Object of ExecutorService interface used for timed execution of Placement
* Planner.
*/
ExecutorService executor = Executors.newFixedThreadPool(1);
/**
* Creating a final List of Result type.
*/
final List<Result> resultList = new ArrayList<Result>();
/**
* set the executor thread working
*/
Future<?> future = executor.submit(new Runnable() {

public void run() {

try {
Result result = new Result();
PlacementPlanner planner = new PlacementPlanner();

result.setRequestMapACK(planner.getRequestResult(
requestMap, systemConfig, request, hostData,
serviceLevelData, transactionID,
configFileLocation));

resultList.add(result);
} catch (Exception e) {
System.out.println("Exception in run method in invokePlacementPlannerWithTimeout method in Controller");
throw new RuntimeException(e);
}
}

});

try {
/**
* invoking the future task with specified timeout.
*/
// System.out.println(timeoutSecs);
future.get(timeoutSecs, TimeUnit.MILLISECONDS);

/**
* Shutting down the service after successful execution.
*/
executor.shutdownNow();
} catch (Exception e) {
/**
* Shutting down the service if timeout is occured.
*/
executor.shutdownNow();

/**
* Canceling the task for future use.
*/
future.cancel(true);

System.out.println("Timeout Occureed.");
Runtime.getRuntime().exec("taskkill /F /IM " + "QNSim.exe*");
}
return resultList;
}

最佳答案

根据 javadoc

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate

因此,shutdownNow() 不保证任务立即终止。

关于java - executor.shutDownNow() 不会停止执行内部方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13038395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com