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 )  {

  RunUpInt runnableObj1 = new RunUpInt ( );
  RunUpInt runnableObj2 = new RunUpInt ( );

  Thread thread1 = new Thread ( runnableObj1 );
  Thread thread2 = new Thread ( runnableObj2 );

  thread1.start();
  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, runnableObj1 and runnableObj2, are instantiated as objects of type RunUpInt. Since RunUpInt was declared to implement Runnable, they will also be recognized as objects of type Runnable, as well.

Next, two threads -- thread1 and thread2 -- are created using the Thread constructor that takes a Runnable object as an argument.

Third, each new thread's start method is called 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 Implements 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] );
  }  else  {
  delay1 = 10;  // default value
  delay2 = 55;  // default value
  }  // end else

  RunUpInt runnableObj1 = new RunUpInt ( "Thread 1", delay1 );
  RunUpInt runnableObj2 = new RunUpInt ( "            Thread 2", delay2 );

  Thread thread1 = new Thread ( runnableObj1 );
  Thread thread2 = new Thread ( runnableObj2 );

  thread1.start();
  thread2.start();

}  // end main

}  // end RunUpInt