Home Segments Top Top Previous Next

885: Mainline

You can slow down a looping thread by adding sleep expressions. They must be in trycatch expressions to handle interruptions.

The following version of DemoThread prints Looping..., every 200 milliseconds, ad nauseam.

public class DemoThread extends Thread { 
 public static void main (String argv []) { 
  DemoThread thread = new DemoThread(); 
  thread.start(); 
 } 
 public void run () { 
  while (true) { 
   System.out.println("Looping..."); 
   try{sleep(200);}                              
   catch (InterruptedException e) {}      
  } 
 } 
}