Lesson 47 +10 XP

Java Threads

Java Threads

Threads let a program do multiple things at the same time. Each thread runs a separate flow of execution inside the same program.

Two ways to create a thread

  1. Extend the Thread class.
  2. Implement the Runnable interface.

Extending Thread

public class Main extends Thread {
  public void run() {
    System.out.println("This code is running in a thread");
  }

  public static void main(String[] args) {
    Main thread = new Main();
    thread.start();
    System.out.println("This code is outside of the thread");
  }
}

Call start() to begin the thread. It runs the run() method.

Implementing Runnable

public class Main implements Runnable {
  public void run() {
    System.out.println("This code is running in a thread");
  }

  public static void main(String[] args) {
    Main obj = new Main();
    Thread thread = new Thread(obj);
    thread.start();
    System.out.println("This code is outside of the thread");
  }
}

Running threads concurrently

Main thread1 = new Main();
thread1.start();

Main thread2 = new Main();
thread2.start();

Both threads run at the same time, and the output order can vary.

Thread safety

When several threads share data, they can interfere with each other. Use careful synchronization to keep shared data consistent.

TL;DR

  • Threads run multiple tasks at the same time.
  • Extend Thread or implement Runnable.
  • Call start() to run a thread.