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 Runnableappraoch; 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 RunUpIntIn this construct, the class,
RunUpIntis defined to beRunnable. When it is instantiated and execution begins, itsmainmethod is called, as usual. There, however, new and wondrous things begin happening. First, two variables,runnableObj1andrunnableObj2, are instantiated as objects of typeRunUpInt. 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
Threadconstructor that takes aRunnableobject as an argument.Third, each new thread's
startmethod is called which, in turn, will call itsrunmethod.Thus, by the time we get to the bottom of the
mainmethod, 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, theirmainmethods are never called.Below is the same program shown in the extends thread discussion, implemented using the
Implements Runnableapproach.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