Extending

   

Extending Thread

You can make your class runnable as a thread by extending the class java.lang.Thread. This gives the class direct access to all the thread methods defined in the Thread class. The Thread class defines a run method that you will need to override because the run method in the Thread class does not do anything but return void. The run method is empty and will not do any work for you. You must override the run method and provide the implementation for the particular application.

Listing 11.1 shows the class SimpleThread, which extends the Thread class and overrides the parent's run method.

Listing 11.1 Source Code for SimpleThread.java
 public class SimpleThread extends Thread { // Default Constructor   public SimpleThread()   {      super();   }   // Override the parent's run method to get the work done   public void run()   {     // Do the thread work here   } } 

Note

As stated earlier, just because the Thread class has been extended in the sample code does not mean it will run as a thread if the SimpleThread class is instantiated . As you will see, the start method must be called to start the thread running as a thread.


   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net