JaVa
   

Creating a Thread

There are two ways to create a thread. One is by extending the java .lang.Thread, and the other is by implementing the java.lang .Runnable interface. As the java.lang package is included by default, we don't need to define their package path, so from now on we will refer to them as "Thread" and "Runnable." In order to handle code in our thread, we must define a run method. The Runnable interface defines this very run method as follows.

public interface Runnable
{
 public void run();
}


The thread class itself implements the Runnable interface and therefore defines its own version of the run method, which does nothing and exits immediately, beautifully placed for us to override with our own implementation. In order to terminate a thread, simply let the run method exit. Similarly, as the main method is called itself from a thread, that thread will stop shortly after the main method has returned. We will discuss stopping threads later in this chapter. First, let's create our first thread.

JaVa
   
Comments