Creating Thread in java

We can create a java Thread in following 2 ways :
1) By implementing Runnable Interface
2) By extending Thread class


Creating Thread by implementing the Runnable interface

We can create the thread by implementing the Runnable interface.
Runnable interface present in java.lang package and contain only one method i. e run() . In order to create thread , we have to implement Runnable interface and override public void run() method of java.lang.Runnable interface.
Syntax to create Thread

//creating  Thread by using Runnable interface
class UserThread implement Runnable
{
	public void run()
	{
	  //stuff to do for thread
	}
}

Example to create thread by implementing Runnable interface . Thread will print numbers from 1 to 10 .

//create a class which implements java.lang.Interface

class UserThread implements Runnable {

    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.print(i + " ");
        }
    }

}

Starting the above thread in main() method. create a new class which contain main() method.


class Main {
    public static void main(String[] args) {
        //create the object UserThread
        UserThread t = new UserThread();

        /* to start the thread we need to instantiate the Thread class and pass 
         UserThread object i. e (t) to the constructor of Thread class */
        Thread ob = new Thread(t);

        //call start() method of Thread class
        ob.start();
    }

}
1 2 3 4 5 6 7 8 9 10

Creating Thread by extending Thread class

The another way to create a thread is to create a class that extends java.lang.Thread class. The extending class must override the run() method to define the stuff for thread.

//creating thread by extending the java.lang.Thread class

class UserThread extends Thread {

    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.print(i + " ");
        }
    }

}

  Note: to start the User Thread we need to call start() method of Thread class.

now start the thread in main() method.


class Main {

    public static void main(String[] args) {
        //create the object of UserThread
        UserThread t = new UserThread();
        //call start() method  of Thread class to start the Thread
        t.start();
    }

}
1 2 3 4 5 6 7 8 9 10

Best approach to create a Thread in java

Among the two ways of creating a thread , implementing Runnable mechanism is recommended to use.
Creating a Thread by extending java.lang.Thread is not recommended because our class is always extends java.lang.Thread class and hence there is no chance of extending some other class at the same time.