3 回答
TA贡献1852条经验 获得超7个赞
这个怎么样?
我认为使用TimeOut不稳定,因为不需要等待不可预测的下载操作。
您可以转为CompletableFutureusingsupplyAsync进行下载并用于thenApply进行处理/转换并通过join如下方式检索结果:
public class SimpleCompletableFuture {
public static void main(String... args) {
testDownload();
}
private static void testDownload() {
CompletableFuture future = CompletableFuture.supplyAsync(() -> downloadMock())
.thenApply(SimpleCompletableFuture::processDownloaded);
System.out.println(future.join());
}
private static String downloadMock() {
try {
Thread.sleep(new Random().nextInt() + 1000); // mock the downloading time;
} catch (InterruptedException ignored) {
ignored.printStackTrace();
}
return "Downloaded";
}
private static String processDownloaded(String fileMock) {
System.out.println("Processing " + fileMock);
System.out.println("Done!");
return "Processed";
}
}
TA贡献1875条经验 获得超3个赞
如果您想要的是超时练习,您可以尝试以下代码:
long timeout = 10 * 60 * 1000;
long start = System.currentTimeMillis();
while(System.currentTimeMillis() - timeout <= start ){
//Not timeout yet, wait
}
//Time out, continue
这在java库中很常见。
添加回答
举报