我正在用Java做一些多线程工作,我对Future get
方法有疑问。
我有一个ExecutorSevice
提交了n个Callable。提交返回一个Future
,该call
被添加到列表中(稍后在某些代码中)。 Callable的someMethod
方法遍历一个列表,并为列表中的每个项目调用CompletableFuture<T>
并返回一个call
。然后,将“可完成的未来”添加到地图中。
在循环结束时,uglyList
返回包含一堆CompletableFuture的地图。
因此,初始列表(<String,CompletableFuture<String>>
)包含n个get
的映射。
我的问题是,当我在uglyList
的元素上调用CompletableFutures
时,执行被阻止,直到访问了整个列表(作为参数传递给Callable)并且所有get
都具有被插入地图,对吧?
由于我有一个疑问,本示例中的CompletableFutures
是否也可能等待地图中
public class A {
private class CallableC implements Callable<Map<String,CompletableFuture<String>>> {
private List<String> listString;
Map<String,CompletableFuture<String>> futureMap;
public CallableC(List<String> listString) throws Exception {
this.listString = listString;
this.futureMap = new HashMap<>();
}
@Override
public Map<String,CompletableFuture<String>> call() throws Exception {
for (int j = 0; j < listString.size(); ++j) {
CompletableFuture<String> future = someMethod();
futureMap.put(listString.get(i),future);
}
return futureMap;
}
}
public void multiThreadMethod(List<String> items) throws Exception {
List<Future<Map<String,CompletableFuture<String>>>> uglyList = new ArrayList<>();
int coresnumber = (Runtime.getRuntime().availableProcessors());
// This method split a List in n subList
List<List<String>> splittedList = split(items,coresnumber);
ExecutorService executor = Executors.newFixedThreadPool(coresnumber);
try {
for (int i = 0; i < coresnumber; ++i) {
threads.add(executor.submit(new CallableC(splittedList.get(i),)));
}
for (int i = 0; i < coresnumber; ++i) {
uglyList.get(i).get(); //here
}
} catch (Exception e) {
// YAY errors
}
finally {
executor.shutdown();
}
}
}
的完成?我不知道如何测试
if (Modernizr.video) {
// let's play some video!
} else {
// no native video support available :(
// maybe check for QuickTime or flash instead
}