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
RunnableandThread start()vsrun(), and waiting withjoin()- Race conditions and why they happen
synchronizedmethods andAtomicInteger- Thread pools with
ExecutorServiceandFuture
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
Runnabledescribes the work; here it is a lambda. AThreadobject runs it. start()creates a new thread and runs the task there. Callingrun()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()makesmainwait until a thread finishes. It can throwInterruptedException, whichmaindeclares.
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
synchronizedmethod lets only one thread run it at a time, sosafeCountis 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.submithands them tasks; a task that returns a value is aCallable, and its result arrives in aFuture.future.get()waits for that result.- Always call
shutdown()on a pool, otherwise its threads keep the program alive.
Concurrency Toolbox
| Tool | Use it for |
|---|---|
synchronized | Protecting a block or method so one thread at a time runs it |
AtomicInteger, AtomicLong | Safe counters and simple shared numbers |
ConcurrentHashMap | A map shared by many threads |
ExecutorService | Running many tasks on a fixed set of threads |
CompletableFuture | Chaining asynchronous steps without blocking |
| Virtual threads (Java 21) | Very many lightweight threads for I/O-heavy servers: Executors.newVirtualThreadPerTaskExecutor() |
Common Mistakes
- Calling
run()instead ofstart(). - Sharing mutable data without synchronization, which causes race conditions that may appear only occasionally.
- Deadlock: two threads each holding a lock the other needs. Acquire locks in a consistent order.
- 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
RunnableorCallable; run it withstart()or an executor. join()andFuture.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.
