Reading history

Java Multithreading: Threads, synchronized and ExecutorService

5 min read 0 views

Learn Java multithreading: Runnable and Thread, start vs run, join, race conditions, synchronized, AtomicInteger, thread pools with ExecutorService and Future.

A thread is an independent path of execution inside a program. Running several threads lets a server handle many users at once, keeps an app responsive while it downloads a file, and uses all the cores of a modern processor. Threads also bring a new kind of bug, where two threads change the same data at the same time. This lesson shows how to start threads, wait for them, avoid race conditions and use thread pools.

In this lesson you will learn

  • Creating threads with Runnable and Thread
  • start() vs run(), and waiting with join()
  • Race conditions and why they happen
  • synchronized methods and AtomicInteger
  • Thread pools with ExecutorService and Future

Starting Threads

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Runnable task = () -> {
            String name = Thread.currentThread().getName();
            int sum = 0;
            for (int i = 1; i <= 1000; i++) sum += i;
            System.out.println(name + " finished, sum=" + sum);
        };

        Thread t1 = new Thread(task, "worker-1");
        Thread t2 = new Thread(task, "worker-2");
        t1.start();                       // runs task in a new thread
        t2.start();
        t1.join();                        // wait for both to finish
        t2.join();
        System.out.println("main continues after join");
    }
}

Output (the order of the first two lines can vary)

worker-1 finished, sum=500500
worker-2 finished, sum=500500
main continues after join
  • A Runnable describes the work; here it is a lambda. A Thread object runs it.
  • start() creates a new thread and runs the task there. Calling run() directly would simply run it in the current thread, with no concurrency.
  • The two workers run at the same time, so which finishes first depends on the operating system’s scheduler. Never rely on thread order.
  • join() makes main wait until a thread finishes. It can throw InterruptedException, which main declares.

Race Conditions and Thread Pools

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    static int unsafeCount = 0;
    static int safeCount = 0;
    static synchronized void safeIncrement() { safeCount++; }

    public static void main(String[] args) throws Exception {
        AtomicInteger atomic = new AtomicInteger();
        Runnable work = () -> {
            for (int i = 0; i < 100_000; i++) {
                unsafeCount++;            // race condition
                safeIncrement();          // one thread at a time
                atomic.incrementAndGet(); // lock-free and safe
            }
        };
        Thread a = new Thread(work), b = new Thread(work);
        a.start(); b.start(); a.join(); b.join();
        System.out.println("unsafe correct? " + (unsafeCount == 200_000));
        System.out.println("synchronized: " + safeCount + ", atomic: " + atomic.get());

        ExecutorService pool = Executors.newFixedThreadPool(3);
        List<Future<Integer>> results = new ArrayList<>();
        for (int n = 1; n <= 4; n++) {
            final int k = n;
            results.add(pool.submit(() -> k * k));   // Callable returns a value
        }
        int total = 0;
        for (Future<Integer> f : results) total += f.get();  // get() waits
        pool.shutdown();
        System.out.println("sum of squares 1..4 = " + total);
    }
}

Output

unsafe correct? false
synchronized: 200000, atomic: 200000
sum of squares 1..4 = 30
  • Two threads each increment the counters 100,000 times, so every counter should reach 200,000.
  • unsafeCount++ is really three steps: read, add one, write back. When both threads read the same old value, one update is lost. This is a race condition, and the result is wrong and different on each run.
  • A synchronized method lets only one thread run it at a time, so safeCount is always correct.
  • AtomicInteger.incrementAndGet() performs the read-add-write as one indivisible step, without a lock, and is usually faster for simple counters.
  • Executors.newFixedThreadPool(3) creates three reusable threads. submit hands them tasks; a task that returns a value is a Callable, and its result arrives in a Future. future.get() waits for that result.
  • Always call shutdown() on a pool, otherwise its threads keep the program alive.

Concurrency Toolbox

ToolUse it for
synchronizedProtecting a block or method so one thread at a time runs it
AtomicInteger, AtomicLongSafe counters and simple shared numbers
ConcurrentHashMapA map shared by many threads
ExecutorServiceRunning many tasks on a fixed set of threads
CompletableFutureChaining asynchronous steps without blocking
Virtual threads (Java 21)Very many lightweight threads for I/O-heavy servers: Executors.newVirtualThreadPerTaskExecutor()

Common Mistakes

  1. Calling run() instead of start().
  2. Sharing mutable data without synchronization, which causes race conditions that may appear only occasionally.
  3. Deadlock: two threads each holding a lock the other needs. Acquire locks in a consistent order.
  4. Forgetting to shut down an executor, so the program never exits.

Practice Exercises

Exercise 1. Start three threads that each print their own name, and make main print “done” only after all three finish.

Show answer
List<Thread> threads = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
    Thread t = new Thread(() -> System.out.println(Thread.currentThread().getName()), "t" + i);
    threads.add(t);
    t.start();
}
for (Thread t : threads) t.join();
System.out.println("done");

Exercise 2. Why does unsafeCount usually end below 200,000, but never above it?

Show answer

A race can only lose updates (two threads write back the same incremented value); it can never create extra increments. So the total is at most 200,000 and usually less.

Frequently Asked Questions

What is the difference between a process and a thread?

A process is a running program with its own memory. Threads live inside a process and share its memory, which makes communication fast but requires care with shared data.

Should I extend Thread or implement Runnable?

Implement Runnable (or use a lambda) and pass it to a thread or executor. It keeps the task separate from how it is run, and your class stays free to extend something else.

Summary

  • Create work as a Runnable or Callable; run it with start() or an executor.
  • join() and Future.get() wait for results.
  • Shared mutable data needs synchronized, atomics or concurrent collections.
  • Prefer thread pools to creating threads by hand, and always shut them down.

Next: Java static and final Keywords.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *