Starting Threads

Basic ways to start the threads in Java

Ways to Start a Thread

In Java, there are two primary ways to create a new thread:

  • Extending the Thread class
  • Implementing the Runnable interface

1. Extending the Thread Class

Steps for Thread Class

  1. Extend the Thread class
  2. Override the run method
  3. Create an instance of the class extending Thread
  4. Call the start method
class Runner extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Count: " + i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Runner runnerOne = new Runner();
        runnerOne.start();

        Runner runnerTwo = new Runner();
        runnerTwo.start();
    }
}

2. Implementing the Runnable Interface

Steps for Runnable interface

  1. Implement the Runnable interface
  2. Override the run method
  3. Create a Thread instance and pass the Runnable implementation as an argument
  4. Call the start method of the Thread instance
class Runner implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Count: " + i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Thread threadOne = new Thread(new Runner());
        threadOne.start();

        Thread threadTwo = new Thread(new Runner());
        threadTwo.start();
    }
}