fork download
  1. import java.util.Arrays;
  2. import java.util.List;
  3. import java.util.concurrent.Callable;
  4. import java.util.concurrent.CompletionService;
  5. import java.util.concurrent.ExecutionException;
  6. import java.util.concurrent.ExecutorCompletionService;
  7. import java.util.concurrent.ExecutorService;
  8. import java.util.concurrent.Executors;
  9. import java.util.concurrent.atomic.AtomicInteger;
  10.  
  11.  
  12. @SuppressWarnings("javadoc")
  13. class Reactive {
  14.  
  15. private static final AtomicInteger threadId = new AtomicInteger(0);
  16.  
  17. private static Thread threadFactory(Runnable r) {
  18. Thread t = new Thread(r, "RxComputationThreadPool-" + threadId.incrementAndGet());
  19. t.setDaemon(true);
  20. return t;
  21. }
  22.  
  23. private static ExecutorService pool = Executors.newCachedThreadPool(Reactive::threadFactory);
  24.  
  25. public static void main(String[] args) throws InterruptedException, ExecutionException {
  26. List<Callable<String>> tasks = Arrays.asList(
  27. () -> "One: " + Thread.currentThread().getName(),
  28. () -> "Two: " + Thread.currentThread().getName(),
  29. () -> "Three: " + Thread.currentThread().getName()
  30. );
  31.  
  32. CompletionService<String> completor = new ExecutorCompletionService<>(pool);
  33.  
  34. int count = tasks.size();
  35. tasks.stream().forEach(completor::submit);
  36. for (int i = 0; i < count; i++) {
  37. System.out.println("Received: " + completor.take().get() + " at " + Thread.currentThread().getName());
  38. }
  39.  
  40. }
  41.  
  42. }
  43.  
Success #stdin #stdout 0.21s 321472KB
stdin
Standard input is empty
stdout
Received: One: RxComputationThreadPool-1 at main
Received: Three: RxComputationThreadPool-1 at main
Received: Two: RxComputationThreadPool-2 at main