Java Create Thread

In most general cases, you create a thread by instantiating an object of the type Thread.

Java defines the following two ways in which this can be attained :

Now let's discuss each method one by one.

Implement Runnable in Java

The easiest way to create a thread is to create a class that implements the Runnable interface.

The Runnable abstracts a unit of executable code. You can construct a thread on any object that implements the Runnable. To implement Runnable, a class require only implement a single method called run(), which is declared like this:

public void run()

Inside the run() method, you will define the code that constitutes the new thread. It is important to understand that the method run() can call the other methods, use other classes, and declare variables, just like the main thread can. The only difference is that the method run() establishes the entry point for another, concurrent thread of execution within your program. This thread will end when the method run() returns.

After you create a class that implements the Runnable, you will instantiate an object of Thread type from within that class. Thread defines several constructors. The one that we will use is shown here :

Thread(Runnable threadOb, String threadName)

In this constructor, threadOb is an instance of a class that implements the Runnable interface. And this defines, where the execution of the thread will start. The name of the new thread is specified by threadName.

After the new thread is created, will not start running until when you call its method start(), which is declared within Thread. In essence, the start() method executes a call to run() method. The start() method is shown below :

void start()

Java Create Thread Example

Below is an example that creates a new thread and starts it running :

/* Java Program Example - Java Creating a Thread
 * Implement Runnable interface 
 * Create a second thread 
 */
 
 class NewThread implements Runnable
 {
     Thread thr;
     
     NewThread()
     {
         /* create a new, second thread */
         thr = new Thread(this, "Demo Thread");
         System.out.println("Child thread : " + thr);
         thr.start();        // start the thread
     }
  
 
     /* this is the entry point for second thread */
     public void run()
     {
         try
         {
             for(int n=5; n>0; n--)
             {
                 System.out.println("Child thread : " + n);
                 Thread.sleep(500);
             }
         }
         catch(InterruptedException e)
         {
             System.out.println("Child interrupted");
         }
         
         System.out.println("Exiting child thread...");
     }
 }
    
 class JavaProgram
 {
     public static void main(String args[])
     {
         
         new NewThread();     // create a new thread
         
         try
         {
             for(int n=5; n>0; n--)
             {
                 System.out.println("Main Thread : " + n);
                 Thread.sleep(1000);
             }
         }
         catch(InterruptedException e)
         {
             System.out.println("Main thraed interrupted");
         }
       
         System.out.println("Main thread exiting");
                 
     }
 }

Within the NewThread's constructor, a new Thread object is created by this statement:

thr = new Thread(this, "Demo thread");

Passing this as the first argument which indicates that you want the new thread to call the method run() on this object. Next, start() is called, which starts the thread of execution starting at the method run(). This cause the child thread's for loop to begin. After calling the start() method, NewThread's constructor returns to the main() method. When the main thread resumes, it enters its for loop. And both the threads continue running, sharing the CPU in single-core systems, until their loops finish. The output produced by the this program is shown here:

java create thread

As mentioned earlier, in a multithreaded program, often the main thread must be the final thread to finish running. In fact, for some older JVMs, if the main thread finishes before the child thread has completed, then the Java run-time system may "hang". The preceding program ensures that the main thread finishes last, as the main thread sleeps for 1,000 milliseconds between iterations, but the child thread sleeps for 500 milliseconds only. This causes the child thread to terminate earlier than the main thread. Soon, you will see a better way to wait for a thread to finish.

Extend Thread

The second style to create a thread is to create a new class that extends the Thread, and then to create an instance of the class. The extending class must override the run(), which is the entry point for the new thread. It must also call the method start() to start the execution of the new thread.

Example

Following is the preceding program rewritten to extend Thread :

/* Java Program Example - Java Creating a Thread
 * Extending Thread
 * Create a second thread by extending Thread 
 */
 
 class NewThread extends Thread
 {
     NewThread()
     {
         /* create a new, second thread */
         super("Demo Thread");
         System.out.println("Child thread : " + this);
         start();        // start the thread
     }
  
 
     /* this is the entry point for second thread */
     public void run()
     {
         try
         {
             for(int n=5; n>0; n--)
             {
                 System.out.println("Child thread : " + n);
                 Thread.sleep(500);
             }
         }
         catch(InterruptedException e)
         {
             System.out.println("Child interrupted..!!");
         }
         
         System.out.println("Exiting child thread...");
     }
 }  
 
 class JavaProgram
 {
     public static void main(String args[])
     {
         
         new NewThread();     // create a new thread
         
         try
         {
             for(int n=5; n>0; n--)
             {
                 System.out.println("Main Thread : " + n);
                 Thread.sleep(1000);
             }
         }
         catch(InterruptedException e)
         {
             System.out.println("Main thraed interrupted..!!");
         }
       
         System.out.println("Exiting main thread");
                 
     }
 }

The above Java program produce the same output as of above program, shown below :

java implement extend thread

As you can see, the child thread is created by instantiating an object of NewThread, which is derived from Thread.

Notice here, the call to the super() method within the NewThread. This invokes the following form of the Thread constructor:

public Thread(String threadName)

In this statement, the threadName specifies the name of the thread

Java Online Test


« Previous Tutorial Next Tutorial »