Extends Thread

In the discussion that follows, we will look, first, at a basic java construct that shows the barebones requirements for a multithreaded program using the Extends Thread appraoch; after that, we will look at a very simple example program that performs a trivial, but observable operation.
class RunUpExt   {
public static void main ( String [ ] args )  {
  MyThread thread1 = new MyThread ( "Thread 1");
  MyThread thread2 = new MyThread ( "Thread 2" );
  thread1.start();
  thread2.start();
}  // end main
}  // end RunUpInt

class MyThread extends Thread  {
MyThread ( String id ) {
  super ( id );
}  // end constructor
public void run ()  {
}  // end run
}  // end MyThread
In this construct, we have two classes, RunUpExt and MyThread. When RunUpExt is instantiated and execution begins, its main method is called. There, two instances of MyThread are created and, following, the start method for each is called.

Thus, three objects are created: one instance of RunUpExt and two instances of MyThread.

Following is an example multithread application implemented by extending Thread:

class RunUpExt   {
public static void main ( String [ ] args )  {
int delay1, delay2;
  if ( args.length == 2 )  {
    delay1 = Integer.parseInt ( args[0] );
    delay2 = Integer.parseInt ( args[1] );
  }  // end if
  else  {  
    delay1 = 10;  // default value
    delay2 = 55;  // default value
  }  // end else
  MyThread thread1 = new MyThread ( "Thread 1", delay1 );
  MyThread thread2 = new MyThread ( "            Thread 2", delay2 );
  thread1.start();
  thread2.start();
}  // end main
}  // end RunUpInt

class MyThread extends Thread  {
int delay;
String lbl;
MyThread ( String id, int d ) {
  super ( id );
  lbl = id;
  delay = d; ;
}  // end constructor
public void run ()  {
  try  {
    for ( int i = 0; i < 20; i++)  {
      System.out.println ( lbl + ": " + i );
      Thread.sleep ( delay );
    }  // end for
  }  // end try
  catch ( InterruptedException except)  {
    return;
  }  // end catch
}  // end run
}  // end MyThread
Note the "substantial" amount of application-specific code that is included in the run of MyThread. In many cases, it is more convenient to locate such code in the primary class of the applet or application. the option shown next provides a "natural" way of doing this.