Why Concurrency: Processes, Threads and the Main Thread in Java
Every Java program runs as a process and starts on one thread, main. One cook takes 15 seconds for soup and salad; a second thread, Jack, brings it to 10. Then two threads add to one counter a million times each and count less than 2,000,000.
What you will learn
- Explain what a process and a thread are, and that every Java program starts on main
- Read the process id, core count and current thread from Java
- Show how a second thread with start and join makes work overlap
- Explain why two threads updating one counter lose updates
Before you start
- Java methods and overloading
- Java lambdas and functional interfaces
This lesson uses a kitchen: first one cook, then two cooks, then two cooks sharing one counter. Along the way you meet processes, threads and the main thread. One note before the code: with more than one thread, the order of lines and the timings can differ from run to run, so the outputs below are from one run.
Every program starts on one thread
package org.studyeasy.s06l01;
public class Ex01_MainThread {
static void placeOrder(String dish) {
// a method runs on the same thread as the code that called it
String who = Thread.currentThread().getName();
System.out.println(dish + " ordered on: " + who);
}
public static void main(String[] args) {
Thread me = Thread.currentThread(); // who is running this line?
System.out.println("Name: " + me.getName());
System.out.println("Id: " + me.threadId());
placeOrder("Caesar Salad");
placeOrder("Margherita");
}
}
Name: main
Id: 3
Caesar Salad ordered on: main
Margherita ordered on: main
When you run a program, the operating system starts a process: your running program in its own sandbox, with a heap for values its threads share. Java starts one thread for you, called main. Thread.currentThread() hands back the thread running that line. The id is just the one printed this time. A method call stays on the caller's thread, so both orders are on main; no new thread was made.
long pid = ProcessHandle.current().pid();
int cores = Runtime.getRuntime().availableProcessors();
The operating system numbers every process it runs, and availableProcessors() gives the number of CPU cores. Both differ per machine and per run (on the recording machine it was 22 cores). Each core runs one thread at a time, so more cores let more threads run together.
One cook, one dish at a time
// cooking = being busy for a few seconds
static void cook(String dish, int seconds) {
System.out.println("main starts " + dish);
try {
Thread.sleep(seconds * 1000); // 1000 ms = 1 second
} catch (InterruptedException e) { }
System.out.println("main finished " + dish);
}
long start = System.currentTimeMillis(); // note the time
cook("Soup", 10); // 10 seconds
cook("Salad", 5); // starts only after the soup
long seconds = (System.currentTimeMillis() - start) / 1000;
System.out.println("Total: " + seconds + " seconds");
main starts Soup
main finished Soup
main starts Salad
main finished Salad
Total: 15 seconds
Thread.sleep pauses the current thread. While main waits for the soup, it can't do anything else, so the times add up: 10 plus 5.
A second cook beside main
Thread jack = new Thread(() -> cook("Soup", 10), "Jack");
jack.start(); // Jack starts the soup: 10 seconds
cook("Salad", 5); // at the same time, main makes the salad
System.out.println("main waits for Jack");
jack.join(); // main stops here until Jack is done
main starts Salad
Jack starts Soup
main finished Salad
main waits for Jack
Jack finished Soup
Total: 10 seconds
Creating a Thread doesn't start it; start() does. Then Jack cooks the soup while main makes the salad, so the two "starts" lines may swap places on another run. join() makes main wait for Jack; without it, Total would print too early. Call jack.run() instead of start() and no new thread is made: main cooks both, 15 seconds again.
Two words you'll hear a lot: concurrency is jobs taking turns, which works even on one core; parallelism is jobs running at the same moment on several cores.
Two threads, one counter
static int orders = 0; // ONE counter, shared by both cooks
Runnable takeOrders = () -> {
for (int i = 0; i < 1_000_000; i++) {
orders++; // read, add 1, write back
}
};
Thread jack = new Thread(takeOrders);
Thread john = new Thread(takeOrders);
jack.start();
john.start();
jack.join(); // wait for both cooks
john.join();
System.out.println("Expected: 2000000");
System.out.println("Counted: " + orders);
Expected: 2000000
Counted: 1233886
The count is less than two million, and it's different on every run. orders++ is really three steps: read, add one, write back. Say orders is 41. Both threads read 41, both add one, Jack writes 42, and John also writes 42, not 43. One update is lost, and over two million steps that happens again and again. This is a race condition; fixing it is the subject of race conditions and synchronized.
Recap
| Idea | In code |
|---|---|
| Process | ProcessHandle.current().pid() |
| Current thread | Thread.currentThread().getName() is main |
| Start a second thread | new Thread(task, "Jack").start() |
| Wait for it | jack.join() |
| Shared data | needs care: orders++ loses updates |
Next: the ways to create threads in Thread, Runnable and lambdas.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Creating Threads in Java: Thread, Runnable and Lambdas
Three ways to give a thread its job: an InvoiceMailer that extends Thread, a ReportTask record that implements Runnable, and a lambda. worker.run() prints main, worker.start() prints backup-worker, and two cashiers, Jack and Liam, scan items in an order that changes every run.
Java Thread Lifecycle: sleep, join and interrupt
A courier thread walks from NEW through RUNNABLE and TIMED_WAITING to TERMINATED while main WAITs at join. An interrupt wakes a sleeping download on report-3: one version retries it, the other returns. And a daemon status thread dies when the last user thread ends.
Java Race Conditions and synchronized
Two cashiers each sell a million tickets on one counter and the total comes out short, a different number every run, because sold++ is read, add, write. A synchronized method or a synchronized block on one shared lock gives exactly 2,000,000; a new Object() lock protects nothing.
Java volatile and Atomic Variables
main sets a volatile running flag to false and the sync job finishes batch 3, sees the change and exits. But volatile can't make views++ one step, so two threads still lose updates. An AtomicInteger with incrementAndGet counts web and mobile visits to exactly 200,000.
