title: How to wait for a thread that spawns it's own thread?
body: <p>I'm trying to test a method that does it's work in a separate thread, simplified it's like this:</p>
  
  <pre><code>public void methodToTest()
  {
      Thread thread = new Thread()
      {
          @Override
          public void run() {
              Clazz.i = 2;
          }
      };
      thread.start();
  }
  </code></pre>
  
  <p>In my unit test I want to test that Clazz.i == 2, but I can't do this because I think that the assert is run before the thread changes the value. I thought of using another thread to test it and then use join to wait but it still doesn't work.</p>
  
  <p>SSCCE:</p>
  
  <pre><code>@Test
  public void sscce() throws InterruptedException
  {
      Thread thread = new Thread()
      {
          @Override
          public void run() {
              methodToTest()
          }
      };
      thread.start();     
      thread.join();  
      AssertEquals(2, Clazz.i);
  }
  
  public static class Clazz
  {
      public static int i = 0;
  }
  </code></pre>
  
  <p>I think this is because the test main code creates a thread that is waiting (joined) to the 2nd thread, but the 2nd thread doesn't do the work, it creates another thread to do the work and then finishes, which continues the first thread, while the third thread does the <code>Clazz.i = 2</code> after the assertion.</p>
  
  <p>How can I make it so that the first thread waits for the thread that it starts <strong>as well as any threads that that thread starts</strong>?</p>