title: Confused about the "Print in Order" problem on LeetCode
body: <p>This should be an easy problem on multithreading: <a href="https://leetcode.com/problems/print-in-order/" rel="nofollow noreferrer">https://leetcode.com/problems/print-in-order/</a>
  <em>&quot;The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second()&quot;</em> And they give this code:</p>
  <pre><code>public Foo() {}
      public void first(Runnable printFirst) throws InterruptedException {
          // printFirst.run() outputs &quot;first&quot;. Do not change or remove this line.
          printFirst.run();
      }
      public void second(Runnable printSecond) throws InterruptedException {
          // printSecond.run() outputs &quot;second&quot;. Do not change or remove this line.
          printSecond.run();
      }
      public void third(Runnable printThird) throws InterruptedException {
          // printThird.run() outputs &quot;third&quot;. Do not change or remove this line.
          printThird.run();
      }
  </code></pre>
  <p>**Seems I can solve it using Thread.join as below, but what I don't understand is why they pass the instance of Runnable to each method, and how to properly do it because the below code will print each message twice - once because Thread.start() will invoke the corresponding run() method, and once from calling that method directly. I understand that this is the wrong way to do it, but can't figure out what is the right solution, if we try to utilize the join method. **</p>
  <pre><code>public Foo() throws InterruptedException {
          Runnable r1 = () -&gt; {
              System.out.println(&quot;first &quot;);
          };
          first(r1);
          
          Runnable r2 = () -&gt; {
              System.out.println(&quot;second &quot;);
          };
          second(r2);
          
          Runnable r3 = () -&gt; {
              System.out.println(&quot;third &quot;);
          };
          third(r3);
          
          Thread t1 = new Thread(r1);
          t1.start();
          try {
              t1.join(); // wait for this thread to finish before starting #2
          }
          catch(Exception e) {
              System.err.println(&quot;Thread 1 error&quot;);
          }
          
          Thread t2 = new Thread(r2);
          t2.start();
          
          try {
              t2.join();
          }
          catch(Exception e) {
              System.err.println(&quot;Thread 2 error&quot;);
          }
          
          Thread t3 = new Thread(r3);
          t3.start();
          
          try {
              t3.join();
          }
          catch(Exception e) {
              System.err.println(&quot;Thread 3 error&quot;);
          }
      }```
  </code></pre>