title: Best way for main/calling thread to wait for other threads to complete their tasks: Thread.sleep(), Latch, CompletableFuture, or something else?
body: <p>What's the best way for the main/calling thread to wait for other threads to complete their tasks? I came up with two options; there are probably more.</p>
  <p><strong>Option 1 - Thread.sleep()</strong></p>
  <pre><code>new Thread(() -&gt; System.out.println(&quot;Executed task 1&quot;)).start();
  new Thread(() -&gt; System.out.println(&quot;Executed task 2&quot;)).start();
  Thread.sleep(1000);
  </code></pre>
  <p><strong>Option 2 - Latch</strong></p>
  <pre><code>CountDownLatch latch = new CountDownLatch(2);
  
  new Thread(() -&gt; {
          System.out.println(&quot;Executed task 1&quot;);
          latch.countDown();
      }).start();
  
  new Thread(() -&gt; {
           System.out.println(&quot;Executed task 2&quot;);
           latch.countDown();
       }).start();
  
  latch.await(1, TimeUnit.SECONDS);
  </code></pre>
  <p><strong>Option 3 - CompletableFuture</strong></p>
  <pre><code>CompletableFuture&lt;Void&gt; future1 = CompletableFuture.runAsync(() -&gt; System.out.println(&quot;Executed task 1&quot;));
  CompletableFuture&lt;Void&gt; future2 = CompletableFuture.runAsync(() -&gt; System.out.println(&quot;Executed task 2&quot;));
  CompletableFuture.allOf(future1, future2).join();
  </code></pre>
  <p><strong>Option 4 - ??</strong></p>