How To: Run A Loop In A Java Thread

Here is a normal loop:

    while(true)
    {
      ...
      if (...)
        break;
      ...
    }
    System.out.println("loop is finished...");

The statements inside the loop are executed over and over again until a break statement causes an exit from the loop. Only after exiting the loop is the print statement ever reached.


Here is a loop that runs in a separate "thread", enabling the program to spin-off the loop as a separate process, while it continues on to the print statement and beyond:

    new Thread(new Runnable()
    {
      public void run()
      {
        while(true)
        {
          ...
          if (...)
            break;
          ...
        }
      }
    }).start();
    System.out.println("loop is running...");

In the above code, the print statement is reached after the loop starts, but before it finishes! When the break statement is reached, the thread ends -- it does re-execute the print statement.

Hint: To cause the loop to pause for a short time, use this code:

          // pause for 1 second
          try{Thread.sleep(1000);}
          catch(Exception e){}


// sample program
public class ThreadTest
{
  public static void main(String[] argv)
  {
    // start a loop
    new Thread(new Runnable()
    {
      public void run()
      {
        for (int i = 0; i < 10; i++)
        {
          System.out.println("1st loop...");
          try{Thread.sleep(1000);} // 1 second pause
          catch(Exception e){}
        }
      }
    }).start();

    // start a 2nd loop
    new Thread(new Runnable()
    {
      public void run()
      {
        for (int i = 0; i < 20; i++)
        {
          System.out.println("2nd loop...");
          try{Thread.sleep(314);} // 0.314 second pause
          catch(Exception e){}
        }
      }
    }).start();

    System.out.println("Both loops started.");
  }
}