next up previous contents
Next: Threads: join() Up: Java Notes Previous: Threads: Stopping

Threads Example 3.1

/**
 *  This code is edited from the book:
 *
 *    Winder, R and Roberts, G (1998) 
 *    Developing Java Software
 *    John Wiley & Sons.
 *
 *  It is copyright (c) 1997 Russel Winder 
 *  and Graham Roberts.
 */
import java.util.Date ;

class ThreadTest3 implements Runnable{
  private static volatile Thread t=new Thread(new ThreadTest3());

  // Display the current time every second, repeating
  // forever.
  public void run(){
	Thread thisThread = Thread.currentThread();
	while (t == thisThread){
	  System.out.println(new Date()) ;
	  // Wait 1 second by calling sleep, which
	  // has to be in a try block. Any exception
	  // thrown is caught and ignored.
	  try{
		Thread.currentThread().sleep(1000) ;
	  }
	  catch (InterruptedException e){ 
	  }
	}
  }
  public static void main(String[] args){
	t.start() ;
	try{
	  Thread.currentThread().sleep(10000) ;
	}
	catch (InterruptedException e){ 
	}
	t=null;
  }
}



Ananda Amatya
9/15/1999