next up previous contents
Next: Threads Example 2.2 Up: Java Notes Previous: Threads: Runnable & sleep()

Threads Example 2.1

/**
 * Adapted from The Java Tutorial
 * Second Edition by Campione, M. and
 * Walrath, K.Addison-Wesley 1998
 */
class SimpleThread extends Thread{
  public SimpleThread(String str){
	super(str);
  }
  public void run(){
	for (int i = 0; i < 10; i++){
	  System.out.println(getName()+": "+(i+1));
	  try {
		sleep((int)(Math.random() * 1000));
	  } catch (InterruptedException e) {}
	}
  }
}
public class TwoThreadsTest{
  public static void main (String[] args){
	SimpleThread t1= new SimpleThread("Thread 1");
	SimpleThread t2= new SimpleThread("Thread 2");
	System.out.println(t1.getName() + 
					   " has priority "+
					   t1.getPriority());
	System.out.println(t2.getName() + 
					   " has priority "+
					   t2.getPriority());
	t1.start();
	t2.start();
  }
}



Ananda Amatya
9/15/1999