Guest User

Untitled

a guest
Jun 21st, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. static class SleepingCallable implements Callable<String> {
  2.  
  3. final String name;
  4. final long period;
  5.  
  6. SleepingCallable(final String name, final long period) {
  7. this.name = name;
  8. this.period = period;
  9. }
  10.  
  11. public String call() {
  12. try {
  13. Thread.sleep(period);
  14. } catch (InterruptedException ex) { }
  15. return name;
  16. }
  17. }
  18.  
  19. final ExecutorService pool = Executors.newFixedThreadPool(2);
  20. final List<? extends Callable<String>> callables = Arrays.asList(
  21. new SleepingCallable("quick", 500),
  22. new SleepingCallable("slow", 5000));
  23. try {
  24. for (final Future<String> future : pool.invokeAll(callables)) {
  25. System.out.println(future.get());
  26. }
  27. } catch (ExecutionException | InterruptedException ex) { }
  28. pool.shutdown();
  29.  
  30. C:devscrap>java CompletionExample
  31. ... after 5 s ...
  32. quick
  33. slow
  34.  
  35. final ExecutorService pool = Executors.newFixedThreadPool(2);
  36. final CompletionService<String> service = new ExecutorCompletionService<String>(pool);
  37. final List<? extends Callable<String>> callables = Arrays.asList(
  38. new SleepingCallable("slow", 5000),
  39. new SleepingCallable("quick", 500));
  40. for (final Callable<String> callable : callables) {
  41. service.submit(callable);
  42. }
  43. pool.shutdown();
  44. try {
  45. while (!pool.isTerminated()) {
  46. final Future<String> future = service.take();
  47. System.out.println(future.get());
  48. }
  49. } catch (ExecutionException | InterruptedException ex) { }
  50.  
  51. C:devscrap>java CompletionExample
  52. ... after 500 ms ...
  53. quick
  54. ... after 5 s ...
  55. slow
  56.  
  57. // this waits until _all_ of the jobs complete
  58. List<Future<Object>> futures = threadPool.invokeAll(...);
  59.  
  60. ExecutorService threadPool = Executors.newFixedThreadPool(2);
  61. ExecutorCompletionService<Result> compService
  62. = new ExecutorCompletionService<Result>(threadPool);
  63. for (MyJob job : jobs) {
  64. compService.submit(job);
  65. }
  66. // shutdown the pool but the jobs submitted continue to run
  67. threadPool.shutdown();
  68. while (!threadPool.isTerminated()) {
  69. // the take() blocks until any of the jobs complete
  70. // this joins with the jobs in the order they _finish_
  71. Future<Result> future = compService.take();
  72. // this get() won't block
  73. Result result = future.get();
  74. // you can then put the result in some other thread pool or something
  75. // to immediately start processing it
  76. someOtherThreadPool.submit(new SomeNewJob(result));
  77. }
Add Comment
Please, Sign In to add comment