JUC:CompletableFuture使用详解
/**
* @author LuckyCurve
* 完成对两个CSV的读取
*/
public class Application1 {
public static void main(String[] args) throws InterruptedException {
List<String> list = Collections.synchronizedList(new LinkedList<>());
CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet("https://gist.githubusercontent.com/CatTail/18695526bd1adcc21219335f23ea5bea/raw/54045ceeae6a508dec86330c072c43be559c233b/movies.csv");
CloseableHttpResponse response = null;
try {
response = client.execute(request);
String[] array = EntityUtils.toString(response.getEntity()).split("\n");
list.addAll(Arrays.asList(array));
} catch (IOException e) {
e.printStackTrace();
}
});
CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet("https://gist.githubusercontent.com/CatTail/18695526bd1adcc21219335f23ea5bea/raw/54045ceeae6a508dec86330c072c43be559c233b/movies.csv");
CloseableHttpResponse response = null;
try {
response = client.execute(request);
String[] array = EntityUtils.toString(response.getEntity()).split("\n");
list.addAll(Arrays.asList(array));
} catch (IOException e) {
e.printStackTrace();
}
});
CompletableFuture.allOf(future1, future2).thenRun(() -> {
System.out.println(list);
System.out.println(list.size());
});
TimeUnit.SECONDS.sleep(100);
}
}最后更新于
