Java Tutorial

Threads

Parallel execution with Runnable, Thread, and join()

What are Java Threads?

In Java, a thread is a "sub-process" or "lightweight process" that runs in the background. It allows your program to perform multiple tasks at the same time (Concurrent Execution). Every Java program has at least one thread: the Main Thread.
java
public class MyThread extends Thread {
    public void run() {
        System.out.println("Running in the background!");
    }
}

MyThread t = new MyThread();
t.start(); // Start the background thread!

Comparisons: Two ways to Create Threads

Wait! Should you extend the Thread class or use the Runnable interface?
MethodBehaviorBest Use Case...
ThreadExtend java.lang.Thread.Quick, simple tasks.
RunnableImplement java.lang.Runnable.Recommended! (Better for long-term design).
java
// Recommended Way: Uses a Lambda!
Thread t = new Thread(() -> {
    System.out.println("Hello from Runnable!");
});
t.start();

Managing Thread Execution

  • start(): Kicks off the background thread (Does NOT call run() directly!).
  • sleep(ms): Pauses the current thread for a specific amount of time.
  • join(): Pauses the calling thread (usually Main) until the background thread finishes its work.
java
Thread t = new Thread(() -> doWork());
t.start();
t.join(); // WAIT for 't' to finish before continuing!

Why use Threads?

  1. Responsiveness: Keep your UI responsive while a background task (like a file download) is running.
  2. Performance: Use all the cores in your modern multi-core CPU.
  3. Scalability: Handle many simultaneous requests (like in a web server).

Summary

TermDescription
ThreadA single execution "path"
MainThe first thread that runs the main() method
RunnableThe task that should be run by the thread
start()Initiate the thread's execution
join()Wait for a thread to die
sleep()Temporarily pause a thread
Best ForMulti-tasking, background processing, CPU intensive apps
SafetyThreads must be carefully managed (See Synchronization!)
ModernUse "Virtual Threads" (Java 21+) for massive scalability
LambdaThreads are perfect with x -> ... logic!
Priorityt.setPriority(10) (Ask the OS to run it faster!)
Daemont.setDaemon(true) (A thread that won't stop the app from exiting)
InterruptedCheck if thread was told to stop with .isInterrupted()
ExceptionInterruptedException must be caught during sleep/join
LifecycleNEW -> RUNNABLE -> BLOCKED -> WAITING -> TERMINATED
NativeThreads are "Mapped" to actual Operating System threads
PlatformBehavior might slightly differ between OSs
StandardEstablished and trusted worldwide for 25+ years
ResourceEach thread uses memory for its own stack (usually ~1MB)
ContextSwitching between 1000s of threads can slow down the CPU
WorkerA generic "Worker" thread that handles background data
UI ThreadNever perform long-running tasks in the main/UI thread!
SafetyGlobal variables are SHARED between all threads!
DeadlockWhen two threads wait for each other FOREVER (AVOID!)
SchedulerThe JVM part that decides which thread runs next