Multithreading

A thread is an independent path of execution within a program. Every Java program has at least one thread automatically — the main thread, which runs your main() method. Multithreading means running more than one thread at the same time, letting a program do multiple things concurrently instead of strictly one step after another.

Creating a Thread by Extending Thread

One way to create a thread is to extend the built-in Thread class and override its run() method with the code you want that thread to execute.

Example: Extending Thread

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

public class ThreadDemo {
  public static void main(String[] args) {
    MyThread thread = new MyThread();
    thread.start(); // starts a new thread
  }
}

Creating a Thread by Implementing Runnable

Extending Thread works, but it uses up your class's one and only chance to extend something, since Java only allows single inheritance. Implementing the Runnable interface instead is generally the preferred approach — your class stays free to extend something else, and the "task to run" stays cleanly separated from the "thread that runs it."

Example: Implementing Runnable

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

public class RunnableDemo {
  public static void main(String[] args) {
    Runnable task = new MyTask();
    Thread thread = new Thread(task);
    thread.start(); // starts a new thread
  }
}

What's happening:

  • MyTask only implements Runnable, so it's still free to extend another class if needed.
  • A plain Thread object is created and handed the Runnable task to execute.
  • Calling start() on the Thread runs the task's run() method on a new thread.

start() vs. run()

This trips up almost everyone at first: calling run() directly does not start a new thread. It just calls the method like any other ordinary method call, running on the current thread. Only start() tells the JVM to create a brand-new thread and schedule run() to execute on it.

thread.run();   // wrong: just a normal method call, no new thread
thread.start(); // correct: launches a new thread that then calls run()
          
Note: Multithreading is a deep topic — real-world concurrent code has to worry about race conditions (two threads modifying shared data at once) and synchronization (coordinating access safely). This page only scratches the surface; treat it as your starting point, not the full picture.
Next up: learn how Java programs read from and write to files with File I/O.