Threads: Doing Things at the Same Time

More than one thing at once

A thread is a separate line of work inside your program. With several threads, a program can do several jobs at the same time – like downloading a file while you keep typing.

Think of it like this: One cook (one thread) makes dinner step by step. Three cooks (three threads) can chop, boil and fry at the same time – but they must be careful not to grab the same knife.

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(() -> {
            for (int i = 1; i <= 3; i++) {
                System.out.println("Worker step " + i);
            }
        });
        worker.start();
        worker.join();
        System.out.println("Main: the worker is finished");
    }
}

Output

Worker step 1
Worker step 2
Worker step 3
Main: the worker is finished
  • new Thread(...) takes the job to do, often as a lambda (a Runnable).
  • start() begins running it alongside main.
  • join() makes main wait until the thread is finished.

Common mistake: Call start(), not run(). run() just runs the code in the current thread, so nothing happens in parallel.

Sharing data safely

When two threads change the same variable at the same time, updates can get lost. synchronized lets only one thread at a time into a method:

class Counter {
    private int count = 0;

    synchronized void increment() {
        count++;
    }

    int get() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Counter c = new Counter();
        Runnable job = () -> {
            for (int i = 0; i < 1000; i++) {
                c.increment();
            }
        };
        Thread t1 = new Thread(job);
        Thread t2 = new Thread(job);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Count: " + c.get());
    }
}

Output

Count: 2000

Without synchronized, the total could sometimes be less than 2000.

Tip: Threads are an advanced topic. For bigger programs, Java has easier tools in java.util.concurrent, such as ExecutorService and AtomicInteger.

HOME LABS COMMUNITY DASHBOARD