Skip to content

Instantly share code, notes, and snippets.

@kuanyingchou
Created October 31, 2017 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuanyingchou/da4ee53996ea212ddce5f5b699579d88 to your computer and use it in GitHub Desktop.
Save kuanyingchou/da4ee53996ea212ddce5f5b699579d88 to your computer and use it in GitHub Desktop.
import java.util.concurrent.*;
public class App {
public static void main(String[] args) throws InterruptedException, ExecutionException {
final int poolSize = 2;
final ExecutorService executorService =
Executors.newFixedThreadPool(poolSize);
final CompletionService<String> completionService =
new ExecutorCompletionService<>(executorService);
completionService.submit(() -> {
Thread.sleep(2);
return "a";
});
completionService.submit(() -> {
Thread.sleep(1);
return "b";
});
for(int i=0; i<2; i++) {
final Future<String> result = completionService.take();
System.out.println(result.get());
}
System.out.println("done");
}
}
/*
result:
b
a
done
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment