In the discussion that follows, we will look, first, at a basic java construct that shows the barebones requirements for a multithreaded program using theImplements 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 ) { Runnable thread1 = new RunUpInt ( ); Runnable thread2 = new RunUpInt ( ); new Thread ( thread1 ).start(); new Thread ( 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,thread1andthread2, are declared to be of type,Runnable; in the same statement, they are instantiated as objects of typeRunUpInt. This is ok since RunUpInt was declared to be Runnable.Next, two (unnamed) threads are created using the
Threadconstructor that takes aRunnableobject as an argument. In the same statement, we also call the new thread'sstartmethod 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
Implemnts 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] ); } // 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