Create a Thread in Java Example

There are two ways to create a thread in Java -
  1. By extending Thread class
  2. By providing a Runnable object

1. By extending Thread class

You can create a new thread simply by extending your class from Thread and overriding it’s run() method.
Below example demonstrates how to create a Thread by extending Thread class:
package com.javaguides.collections.utils;
public class ThreadExample extends Thread {

    @Override
    public void run() {
        System.out.println("Inside : " + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        System.out.println("Inside : " + Thread.currentThread().getName());

        System.out.println("Creating thread...");
        Thread thread = new ThreadExample();

        System.out.println("Starting thread...");
        thread.start();
    }
}
Output:
Inside : main
Creating thread...
Starting thread...
Inside : Thread-0

2. By providing a Runnable object

The Thread class itself implements Runnable with an empty implementation of a run() method.
For creating a new thread, create an instance of the class that implements Runnable interface and then pass that instance to Thread(Runnable target) constructor.
package com.javaguides.collections.utils;
public class RunnableExample implements Runnable {

    public static void main(String[] args) {
        System.out.println("Inside : " + Thread.currentThread().getName());

        System.out.println("Creating Runnable...");
        Runnable runnable = new RunnableExample();

        System.out.println("Creating Thread...");
        Thread thread = new Thread(runnable);

        System.out.println("Starting Thread...");
        thread.start();
    }

    @Override
    public void run() {
        System.out.println("Inside : " + Thread.currentThread().getName());
    }
}
Output:
Inside : main
Creating Runnable...
Creating Thread...
Starting Thread...
Inside : Thread-0

Comments