Starting a Thread


public class MyThread extends Thread {    public void run() {       // do some work    } } // code to use MyThread new MyThread().start();



There are two primary techniques for writing code that will run in a separate thread. You can either implement the java.lang.Runnable interface or extend the java.lang.Thread class. With either approach, you must implement a run() method. The run() method contains the code that you want to execute in the thread. In this phrase, we have extended the java.lang.Thread class. At the point where we want to start the thread, we instantiate our MyTHRead class and call the start() method, which is inherited from the THRead class.

Here, we show how running a thread is accomplished using the other technique of implementing the Runnable interface:

public class MyThread2 implements Runnable {    public void run() {       // do some work    } } // code to use MyThread2 Thread t = new Thread(MyThread2); t.start();


Implementing the Runnable interface is often used in situations in which you have a class that is already extending another class, so it cannot extend the Thread class. Java supports only single inheritance, making it impossible for a class to extend from two different classes. The method in which we start the thread is slightly different. Instead of instantiating the class we defined, as we did when we extended the Thread interface, here we instantiate a Thread object and pass our class that implements Runnable as a parameter to the Thread constructor. We then call the Thread's start() method, which starts the thread and schedules it for execution.

Anther common way of creating a thread is to implement the Runnable interface using an anonymous inner class. We show this method here:

public class MyThread3 {    Thread t;    public static void main(String argv[]) {       new MyThread3();    }    public MyThread3() {       t = new Thread(new Runnable( ) {          public void run( ) {             // do some work          }       });       t.start( );    } }


In this example, all the code is contained within a single class, so it is well encapsulated; this makes it easy to see what is going on. Our Runnable implementation is defined as an inner class, rather than explicitly creating a class that implements the Runnable interface. This method is ideal for small run methods that don't require a lot of interaction with external classes.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

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