title: Java Waiting for all threads to complete
body: <p>Edit: My question is different, it has no relevance to the linked question.</p>
  
  <p>I've following code with completion handler.</p>
  
  <pre><code>FutureTask&lt;Void&gt; futureTask = new FutureTask&lt;Void&gt;(() -&gt; {
      System.out.println("callback");
      return null;
  });
  
  Runnable task = () -&gt; {
      for(int i=0; i&lt;5; i++) {
          System.out.println(Thread.currentThread().getName() + " " + i);
      }
      futureTask.run();
  };
  
  new Thread(task).start();
  new Thread(task).start();
  </code></pre>
  
  <p>Basically I'm looking for completion handler for variable number of tasks, or is there another approach?</p>
  
  <p>I'm inspired from this <a href="https://stackoverflow.com/questions/13473070/how-to-wait-for-all-threads-to-complete">answer</a> but seems it's part of some library while I'm looking for a native solution.</p>
  
  <p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html" rel="nofollow noreferrer">Completable Future</a>??? </p>
  
  <p>Here's my attempt with completable futures with the result handler at the end. </p>
  
  <pre><code>public void test() {
      CompletableFuture
              .supplyAsync(() -&gt; method1())
              .supplyAsync(() -&gt; method2())
              .supplyAsync(() -&gt; result());
  }
  
  public String method1() {
      System.out.println("calling 1");
      return "method1";
  }
  
  public String method2() {
      System.out.println("calling 2");
      return "method2";
  }
  
  public String result() {
      System.out.println("result");
      return "result";
  }
  </code></pre>