title: How do you ensure that a thread executes after another?
body: <p>Sorry if this is a stupid question. I found a solved problem in a book, but the solution doesn’t contain a source code. I proposed a code, but I’m not sure if the code fits the solution specifications. Please correct the code or propose a better code if possible (explanations are welcome). Thanks for the help.</p>
  
  <hr>
  
  <p><strong>Problem :</strong></p>
  
  <p>There are three threads T1, T2 and T3. How do you ensure sequence T1, T2, T3 in Java?</p>
  
  <hr>
  
  <p><strong>Solution :</strong></p>
  
  <p>Sequencing in multi-threading can be achieved by different means but you can simply use join() method of thread class to start a thread when another one is finished its execution. <strong>To ensure three threads execute you need to start the last one first e.g. T3 and then call join methods in reverse order e.g. T3 calls T2.join, and T2 calls T1.join, this ways T1 will finish first and T3 will finish last</strong>.</p>
  
  <hr>
  
  <p><strong>Proposed code :</strong></p>
  
  <pre><code>final Thread t3 = new Thread(new T3()); // assume T3 is a Runnable
  final Thread t2 = new Thread(new T2());
  final Thread t1 = new Thread(new T1());
  
  t3.start();
  t2.start();
  t1.start();
  
  t2.join();
  t1.join();
  </code></pre>