gpt4 book ai didi

java - 超时后如何取消任务?

转载 作者:行者123 更新时间:2023-12-02 05:46:25 25 4
gpt4 key购买 nike

我有一些 Task 执行可能挂起的 I/O 阻塞操作(从 URL 获取文件)

task = new Task<List<WSDLOperation>>() {
@Override
protected List<WSDLOperation> call() {
List<WSDLOperation> services = new ArrayList<>();
try {
services = WSDLService.createService(wsdlURL).getOperations();
} catch (Exception ex) {
LOG.log(Level.WARNING, "Can't reach {0}", wsdlURL);
}
return services;
}
};

}

方法createService可以永远等待,而不会抛出任何Exception。(我使用 Main 类中定义的全局 (static public)ExecutorService 执行任务)。

最佳答案

如何使用 future 并在超时后取消任务:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Test {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Task t = new Task();
Future<String> future = executor.submit(t);

try {
System.out.println("Started..");
System.out.println(future.get(5, TimeUnit.SECONDS)); // throws
// TimeoutException
System.out.println("Finished!");
} catch (TimeoutException e) {
future.cancel(true);
System.out.println("Terminated!");
}
}
}

class Task implements Callable<String> {
@Override
public String call() throws Exception {
for (int i = 0; i < 1000; i++) {
Thread.sleep(1000);
System.out.println("task running!");
}
return "Ready!";
}
}

关于java - 超时后如何取消任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24027314/

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