Implements Runnable

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 Implements Runnable appraoch; after that, we will look at a very simple example program that performs a trivial, but observable operation.
class RunUpInt implements Runnable  {
RunUpInt( ) {
}  // end constructor
public void run ()  {
}  // end run
public static void main ( String [ ] args )  {
  Runnable thread1 = new RunUpInt (  );
  Runnable thread2 = new RunUpInt (  );
  new Thread ( thread1 ).start();
  new Thread ( thread2 ).start();
}  // end main
}  // end RunUpInt
In this construct, the class, RunUpInt is defined to be Runnable. When it is instantiated and execution begins, its main method is called, as usual. There, however, new and wondrous things begin happening. First, two variables, thread1 and thread2, are declared to be of type, Runnable; in the same statement, they are instantiated as objects of type RunUpInt. This is ok since RunUpInt was declared to be Runnable.

Next, two (unnamed) threads are created using the Thread constructor that takes a Runnable object as an argument. In the same statement, we also call the new thread's start method which, in turn, will call its run method.

Thus, by the time we get to the bottom of the main method, we have created three instances of the class, RunUpInt -- the original instance whose main method was called and the two additional instances created when the new threads were created. Note, that with the latter two instances, their main methods are never called.

Below is the same program shown in the extends thread discussion, implemented using the Implemnts Runnable approach.

class RunUpInt implements Runnable  {
int delay;
String lbl;
RunUpInt( String id, int d ) {
  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
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
  Runnable thread1 = new RunUpInt ( "Thread 1", delay1 );
  Runnable thread2 = new RunUpInt ( "            Thread 2", delay2 );
  new Thread ( thread1 ).start();
  new Thread ( thread2 ).start();
}  // end main
}  // end RunUpInt