Back to course

Introduction to Multithreading and the Thread Class

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 46: Introduction to Multithreading

Multithreading allows a program to run multiple parts of its code concurrently. Each concurrent execution path is called a thread.

1. Process vs. Thread

  • Process: An execution environment that has its own complete set of resources (memory, file handlers). Multiple processes run independently.
  • Thread: A lightweight sub-process within a process. Threads share the process's resources (like memory). This makes communication between threads very fast but introduces complexity (thread safety).

2. Creating a Thread (Method 1: Extending Thread)

The simplest way is to subclass the Thread class and override the run() method, which contains the code the thread will execute.

java public class MyThread extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName() + " is running."); // Task code here } }

// Usage: MyThread t1 = new MyThread(); t1.start(); // Invokes the run() method and starts the thread concurrently // t1.run(); // DO NOT call run() directly, it runs synchronously!

3. Creating a Thread (Method 2: Implementing Runnable)

This is the preferred method because it allows your class to extend another class while still defining a thread's task (Java only supports single inheritance).

java public class MyRunnable implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + " is running."); } }

// Usage: Thread t2 = new Thread(new MyRunnable()); t2.start();

4. Lifecycle of a Thread

Threads move through states:

  1. New: Thread object created.
  2. Runnable: Ready to run (in the thread pool).
  3. Running: Currently executing.
  4. Blocked/Waiting: Temporarily inactive (e.g., waiting for I/O or a lock).
  5. Terminated (Dead): Finished execution.