, 여기에 그것을 할 수있는 방법 :
int timeout = 250;
ExecutorService executorService = Executors.newFixedThreadPool(3);
try {
Map<String, CompletableFuture<String>> map =
Stream.of("http://google.com", "http://yahoo.com", "http://bing.com")
.collect(
Collectors.toMap(
// the key will be the URL
Function.identity(),
// the value will be the CompletableFuture text fetched from the url
(url) -> CompletableFuture.supplyAsync(
() -> readUrl(url, timeout),
executorService
)
)
);
executorService.awaitTermination(timeout, TimeUnit.MILLISECONDS);
//print the resulting map, cutting the text at 100 chars
map.entrySet().stream().forEach(entry -> {
CompletableFuture<String> future = entry.getValue();
boolean completed = future.isDone()
&& !future.isCompletedExceptionally()
&& !future.isCancelled();
System.out.printf("url %s completed: %s, error: %s, result: %.100s\n",
entry.getKey(),
completed,
future.isCompletedExceptionally(),
completed ? future.getNow(null) : null);
});
} catch (InterruptedException e) {
//rethrow
} finally {
executorService.shutdownNow();
}
이 당신에게 당신이 URL에 많은 Future
의를 제공하지만, 당신이 볼 수있는 기회를 제공합니다 예외로 인해 실패한 태스크가있는 경우 당신은 이러한 예외, 성공적인 취득에서는의 내용에 관심이 있다면 코드는 간단하게 할 수있다 :
int timeout = 250;
ExecutorService executorService = Executors.newFixedThreadPool(3);
try {
Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
Stream.of("http://google.com", "http://yahoo.com", "http://bing.com")
.forEach(url -> {
CompletableFuture
.supplyAsync(
() -> readUrl(url, timeout),
executorService
).thenAccept(content -> map.put(url, content));
});
executorService.awaitTermination(timeout, TimeUnit.MILLISECONDS);
//print the resulting map, cutting the text at 100 chars
map.entrySet().stream().forEach(entry -> {
System.out.printf("url %s completed, result: %.100s\n",
entry.getKey(), entry.getValue());
});
} catch (InterruptedException e) {
//rethrow
} finally {
executorService.shutdownNow();
}
코드의 모두 (더에만 작은 조금 걸릴 것입니다 약 250 밀리 초 동안 대기의 때문에 결과를 인쇄하기 전에 실행 프로그램 서비스에 태스크 제출). 약 250 밀리 초가 내 네트워크에서 이러한 URL 중 일부를 가져올 수있는 임계 값이지만 전체는 아닙니다. 실험 시간 제한을 자유롭게 조정하십시오.
readUrl(url, timeout)
방법의 경우 Apache Commons IO과 같은 유틸리티 라이브러리를 사용할 수 있습니다. Executor 서비스에 제출 된 태스크는 사용자가 명시 적으로 timeout
매개 변수를 고려하지 않더라도 인터럽트 신호를받습니다. 구현을 제공 할 수는 있지만 문제의 주요 문제의 범위를 벗어났습니다.
답장을 보내 주셔서 감사합니다. 실제로는 awaitTermination이 핵심입니다.) – Wavyx
및 URL 읽기에 대한 유용한 정보 타임 아웃 – Wavyx