Web Analytics

Threading Basics

Advanced ~20 min read

Multithreading allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a Thread.

Creating a Thread

There are two main ways to create a thread in Java:

1. Extend Thread Class

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread running");
    }
}
// Start it:
MyThread t = new MyThread();
t.start();

2. Implement Runnable Interface (Preferred)

Better because you can still extend another class.

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Thread running");
    }
}
// Start it:
Thread t = new Thread(new MyRunnable());
t.start();

Thread Lifecycle

A thread goes through various states: New, Runnable, Running, Blocked/Waiting, Terminated.

Java Thread Lifecycle Diagram

Full Example

Output
Click Run to execute your code

Summary

  • Use start() to execute the run() method in a separate thread.
  • Directly calling run() does not start a new thread.
  • Runnable is generally preferred over extending Thread.