gpt4 book ai didi

java - future 的 get() 方法如何处理超时

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:48:33 25 4
gpt4 key购买 nike

我有点困惑 Future.get(timeout) 如何按照定义在指定的超时时间后通过异常工作,但它在我的测试用例中没有发生。

import java.util.LinkedHashSet;
import java.util.Set;
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;

public class CallableExample {

public static class WordLengthCallable implements Callable<String> {
private String word;
private long waiting;

public WordLengthCallable(String word, long waiting) {
this.word = word;
this.waiting = waiting;
}

public String call() throws InterruptedException {
Thread.sleep(waiting);
return word;
}
}

public static void main(String args[]) throws Exception {
args = new String[] { "i", "am", "in", "love" };
long[] waitArr = new long[] { 3000, 3440, 2500, 3000 };
ExecutorService pool = Executors.newFixedThreadPool(3);
Set<Future<String>> set = new LinkedHashSet<Future<String>>();
int i = 0;
for (String word : args) {
Callable<String> callable = new WordLengthCallable(word, waitArr[i++]);
Future<String> future = pool.submit(callable);
set.add(future);
}
String sum = "";
for (Future<String> future : set) {
try {
sum += future.get(2000, TimeUnit.MILLISECONDS) + ", ";
} catch (Exception e) {
}
}
System.out.print("Result : " + sum);
}
}

输出“上午,在”

它在更改数组(timeArr 值)中的等待时间时表现不同。什么时候使用 get with timeout?

最佳答案

在您的 for 循环中,您等待第一个 future 完成。这可能需要 2000 毫秒。此时所有其他线程都会 hibernate 。因此,其他线程的所有值都少了 2000 毫秒。然后你再等 2000 毫秒,也许你等待返回的 future 。因此,两个或更多线程将成功。

在循环的每次迭代中,您向另一个线程捐赠 2000 毫秒。只有当一个 future 成功返回时,您才会减少对剩余 future 的捐赠。如果您想观察所有 futures 失败,由于 2000 毫秒超时,您也必须并行处理它们。

如果您以这种方式更改部分代码:

Set<Callable<String>> tasks = new HashSet<>();
for (String word : args) {
tasks.add(new WordLengthCallable(word, waitArr[i++]));
}
List<Future<String>> futures = Executors.newFixedThreadPool(3)
.invokeAll(tasks, 2000, TimeUnit.MILLISECONDS);

您应该观察到没有任何任务会成功,因为等待时间为:

3000, 3440, 2500, 3000

对于每个创建的 Callable,都大于 2000。

关于java - future 的 get() 方法如何处理超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22863965/

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