Course contentsShow
← Java
Lesson 2577 of 2,87048. Concurrency FundamentalsFree lesson

Starting Multiple Threads

Launch several threads and observe that they execute concurrently and unpredictably.

Starting Multiple Threads

What you'll learn: You'll see how launching several threads causes them to run concurrently, each progressing in an unpredictable, interleaved manner.

The Core Idea

When you start multiple threads, the JVM's thread scheduler decides when each thread gets CPU time. Unlike sequential code where line 1 always runs before line 2, multiple threads race forward independently. Their execution order is non-deterministic—run the same program twice, and you'll likely see different output patterns.

Think of it like multiple cashiers at a grocery store. All serve customers "at the same time," but you can't predict which cashier will finish first, or which will call "next" at any given moment.

How It Works

Create multiple Thread instances and call start() on each:

public class MultiThreadDemo {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Thread-1: " + i);
            }
        });
        
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Thread-2: " + i);
            }
        });
        
        t1.start();
        t2.start();
    }
}

Typical output (varies each run):

Thread-1: 0
Thread-2: 0
Thread-1: 1
Thread-2: 1
Thread-2: 2
Thread-1: 2
...

Notice the interleaving? Sometimes Thread-1 prints multiple lines before Thread-2 gets a turn; other times they alternate. The scheduler controls this, and you have no guarantees about order.

Why This Matters

Concurrent execution is powerful but introduces unpredictability. You can't assume one thread finishes before another starts. This is the foundation for understanding why coordination mechanisms (locks, synchronization) become necessary later.

Key Takeaway: Starting multiple threads causes them to execute concurrently with unpredictable, interleaved progress—the thread scheduler decides execution order, making output non-deterministic.