Two different ways to start a thread in Java

Threads are lightweight process . Each thread is an instance of class Thread. Each Java program runs on main thread. If want to do some heavy time taking task like like networking call, you should do it in a different thread, Otherwise, the program will hang or the execution will pause.

Think about an android application, suppose you are fetching data from your server and showing it to the user. What will happen if you start fetching the data on main thread ? The application will become unresponsive , isn’t it ? So, we should always run any time taking heavy task on a different thread .

Now, let’s move to the main point. How to create and start a thread ? Java provides two different ways to create a new thread :

  1. By extending java.lang.Thread class
  2. Implementing java.lang.Runnable interface

Let me show you with examples how these methods works :

Example to create a thread by extending java.lang.Thread class :

public class Main {
    public static void main(String[] args) {
    //7
        Thread firstThread = new SampleThread("first-thread");
        Thread secondThread = new SampleThread("second-thread");
    //8
        firstThread.start();
        secondThread.start();
    }
}

//1
class SampleThread extends Thread {

   //2
    public SampleThread(String name) {
        super(name);
    }

   //3
    @Override
    public void run() {
    //4
        System.out.println("Starting " + Thread.currentThread().getName());

        try {
        //5
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    //6
        System.out.println("Ending " + Thread.currentThread().getName());
    }
}

Explanation : The commented numbers in the above program denote the step number below :

  1. Create one class SimpleThread that extends the Thread class. Object of this class will work as a thread.
  2. Creating a constructor for this class will help us to give a name to this thread.
  3. Override run() method of this class. Inside this method, write all the code that you want to execute.
  4. First we are printing the name of the current thread at the start point.
  5. Now, we are forcefully pausing the thread for 5 seconds.
  6. After the thread is executed, we are printing the name again.
  7. Inside the main() method, create two objects of type SimpleThread . The name of the first thread is first-thread and the name of the second thread is second-thread.
  8. Start both threads using start() method of the thread. It will execute the code inside run() method.

Output :

Starting first-thread
Starting second-thread
Ending first-thread
Ending second-thread

Implementing java.lang.Runnable interface :

Now, let’s implement thread by implementing the Runnable interface. This thread will do the same work as the previous one :

public class Main {
    
public static void main(String[] args) {
	//3
    Thread firstThread = new Thread(new SampleThread(),"first-thread");
    Thread secondThread = new Thread(new SampleThread(),"second-thread");
    firstThread.start();
    secondThread.start();
	}
}

//1
class SampleThread implements Runnable {
    //2
    @Override
    public void run() {
    	System.out.println("Starting " + Thread.currentThread().getName());
    try {
    	Thread.sleep(5000);
    } catch (InterruptedException e) {
    	e.printStackTrace();
    }
    	System.out.println("Ending " + Thread.currentThread().getName());
    }
}

Explanation :

  1. Create one class and implement the Runnable interface.
  2. Override the run() method and write down the same code as the previous one. It will print its name at start and end ,and hold for 5 seconds.
  3. Inside the main method of the class, create two Thread objects and pass one new Runnable object to the Thread object. Thread takes one Runnable object and a string as parameter. The string is the name of the thread. Start both thread and it will print the following output :
Starting first-thread
Starting second-thread
Ending first-thread
Ending second-thread

So, both ways priced the same output. Only the implementation is different.

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊