Threads

A thread is a lightweight subprocess, the smallest unit of processing. This tutorial will teach you how to create and manage threads in Java.

Creating a Thread

There are two ways to create a thread in Java:

  • By extending the Thread class
  • By implementing the Runnable interface

Extending the Thread Class


public class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running");
    }
    
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}
      

Implementing the Runnable Interface


public class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Thread is running");
    }
    
    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        thread.start();
    }
}
      

Thread Lifecycle

A thread in Java can be in one of the following states:

  • New – A thread that has been created but not yet started.
  • Runnable – A thread that is ready to run and waiting for CPU time.
  • Blocked – A thread that is waiting for a monitor lock.
  • Waiting – A thread that is waiting indefinitely for another thread to perform a particular action.
  • Timed Waiting – A thread that is waiting for another thread to perform a particular action for a specified waiting time.
  • Terminated – A thread that has exited.

Continue exploring our intermediate tutorials to learn more about Java programming.

Scroll to Top