JaVa
   

Extending a Thread

In order to extend a thread, we use the keyword extends, as we saw in . We can then override its run method and supply our own where we can execute some code. Always remember that the main method is executed in a thread itself. The following example, SimpleThread1, creates a new thread from the main thread and starts its execution.

Code Listing 7-1: SimpleThread1.java
public class SimpleThread1 extends Thread
{
 public void run()
 {
 System.out.println("New thread executing");
 }
 public static void main(String args[])
 {
 SimpleThread1 myThread = new SimpleThread1();
 myThread.start();
 System.out.println("Main's thread executing");
 }
}


Java End example

When you compile and run this example, you could, and I repeat could, get output similar to the following figure.

Java Click To expand
Screenshot-1:

In this code we create a new thread from main and then start it. Notice that we used the Thread method start to, well, start the thread. This will in turn invoke the run method for you. Therefore, you don't need to invoke the run method yourself; simply start the thread. The important thing you need to realize is that the main thread and the new thread are two separate processes and are not executed sequentially. Just because we created and started the new thread from the main method does not mean that the new thread will execute first and then return to main. If that were the case, we may as well just call run as a method. You can view them as almost two separate programs, running alongside one another but under the same program environment. Now, should you compile this source code again, it is quite likely that you will get output similar to the following figure.

Java Click To expand
Screenshot-2:

As you can see, the text output from inside main, in the main thread, is now printed first and the new thread's text printed after. As they are two separate threads, when sections of code inside them are executed is determined by the Java Virtual Machine. However, you can influence the proportion of processor time taken by a thread by setting their priority, as we shall see later.

You may be able to see the main problem with threads, which is handling when they run in concurrence with one another; this is what synchronization is all about, which we will discuss a little later. We can now look at a somewhat more useful way of creating a thread: by implementing the Runnable interface.

JaVa
   
Comments