title: How threads work in Java and how their working is different from basic code inside a method?
body: <p>Basically this code has two threads created in two classes, and they are called from the third class. Each thread has a loop, and it sleeps after each iteration.</p>
  
  <p>(code is in the end)</p>
  
  <p>The output is:</p>
  
  <pre><code>CHECK 0 CHECK
  CHECK 1 CHECK
  run one
  in thread1 
  CHECK 2 CHECK
  run two
  in thread2
  </code></pre>
  
  <p>1) I am not getting any idea why it works this way. I mean it is okay that CHECK 0 CHECK should be printed first. But why does CHECK 1 CHECK get printed before Thread1 (whereas it comes after Thread1 is called in the code) and same for CHECK 2 CHECK and Thread2?</p>
  
  <p>2) If i replace CHECK 2 CHECK with System.exit(0), as in the case above, where printing CHECK 2 CHECK, which is next to Thread2, takes place before running Thread2, Why is System.exit(0) happening after running Thread2 in this case?</p>
  
  <p>Output for second case:</p>
  
  <pre><code>CHECK 0 CHECK
  CHECK 1 CHECK
  run one
  in thread1 
  run two
  in thread2
  </code></pre>
  
  <p>Please tell why this is happening? Why are the threads and code in method, getting mixed up this way?
  I think i don't have any idea about how threads are managed by java. I tried searching a lot, but could not find anything that i could understand.</p>
  
  <p>Code:</p>
  
  <pre><code>public class Thread1 implements Runnable 
  {
  
      public Thread1()
      {
          new Thread(this).start();
      }
  
      public void run() 
      {
          // TODO Auto-generated method stub
          System.out.println("run one");
          try
          {
              for(int i = 0; i &lt; 5;i++)
              {
                  System.out.println("in thread1 ");
                  Thread.sleep(1000);
              }
          }
          catch(Exception e)
          {
              //e.printStackTrace();
          }
      }
  
  }
  
  public class Thread2 implements Runnable 
  {
  
      public Thread2()
      {
          new Thread(this).start();
      }
  
      public void run() 
      {
          // TODO Auto-generated method stub
          System.out.println("run two");
          try
          {
              for(int i=0;i&lt;5;i++)
              {
                  System.out.println("in thread2 ");
                  Thread.sleep(1000);
              }
          }
          catch(Exception e)
          {
              //e.printStackTrace();
          }
      }
  }
  
  public class Threadjava
  {
      public static void main(String[] str)
      {
          System.out.println("CHECK 0 CHECK");
          new Thread1();
          System.out.println("CHECK 1 CHECK");
          new Thread2();
          System.out.println("CHECK 2 CHECK");
          //The above is deleted in the second case
          System.exit(0);
          System.out.println("CHECK 3 CHECK");
      }
  }
  </code></pre>