In the discussion that follows, we will look, first, at a basic java construct that shows the barebones requirements for a multithreaded program using theExtends Threadappraoch; 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 MyThreadIn this construct, we have two classes,RunUpExtandMyThread. When RunUpExt is instantiated and execution begins, itsmainmethod is called. There, two instances ofMyThreadare created and, following, thestartmethod for each is called.Thus, three objects are created: one instance of
RunUpExtand two instances ofMyThread.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 MyThreadNote the "substantial" amount of application-specific code that is included in therunofMyThread. 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.