Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Multithreading

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Multithreading

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
Timeline from 0 to 15 seconds. One cook: main cooks soup from 0 to 10, then salad from 10 to 15, total 15. Two cooks: Jack cooks soup from 0 to 10 while main cooks salad from 0 to 5 and then waits in join until 10, total 10. one cookmainJack Soup 10sSalad 5s Salad 5sjoin: waits Soup 10s 15 s vs 10 s
start runs the work on a new thread so the two overlap; join waits for the slower one.

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

IdeaIn code
ProcessProcessHandle.current().pid()
Current threadThread.currentThread().getName() is main
Start a second threadnew Thread(task, "Jack").start()
Wait for itjack.join()
Shared dataneeds care: orders++ loses updates

Next: the ways to create threads in Thread, Runnable and lambdas.

Keep going in Java · 65 of 79

Previous
Java Streams II: Collectors, groupingBy and flatMap
Next post
Creating Threads in Java: Thread, Runnable and Lambdas
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • Every program starts on one thread
  • One cook, one dish at a time
  • A second cook beside main
  • Two threads, one counter
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.