Tuesday, 30 August 2016

Thread - How to create thread in Java?

We learned the basics of threads, Thread Lifecycle and States in previous post. Now its time to create a thread and run it.

There are two ways to create a thread in Java.

  1. Extending Thread class.
  2. Implementing Runnable interface.
There are other ways also, like by using Callable interface. But in this article we will discuss the basic ways of thread creation. I will write separate articles for other specific ways of thread creation by callable or by using executor framework.

Create thread by extending Thread class - 
The most basic way to create a thread is by extending Thread class and overrides its run() method. Thread class in java extends Object class and implements Runnable interface.
Below is a sample code to create thread by extending Thread class.

package threads;

public class ThreadByExtending extends Thread {

    public void run() {
        System.out.println("ThreadByExtending is in running state.");
    }

    public static void main(String args[]) {
        ThreadByExtending thread = new ThreadByExtending();
        thread.start();
    }
}

Create thread by implementing Runnable interface
By implementing Runnable interface we create a runnable object that is passed to thread constructor for creating a new thread. Runnable interface has only one method run() that needs to be overridden. Below is a sample code to create thread by implementing Runnable interface.

package threads;

public class ThreadByImplementing implements Runnable {
    public void run() {
        System.out.println("ThreadByExtending is in running state.");
    }

    public static void main(String args[]) {
        ThreadByImplementing runnable = new ThreadByImplementing();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}


Which way of Thread creation should be used -
Both ways of creating thread are good and can be used. But implementing Runnable interface is preferable because if we want to extend some other class also, then that can be extended with Runnable method only. 

No comments:

Post a Comment