🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Java Multithreading Basics — Thread, Runnable, Synchronization

Java Advanced TopicsMultithreading🟢 Free Lesson

Java Multithreading Basics — Thread, Runnable, Synchronization

Learning Objectives

  • Create threads by implementing Runnable or extending Thread
  • Describe the basic thread life cycle
  • Explain why race conditions happen on shared data
  • Protect shared state with synchronized methods

Overview

A thread is a single sequence of instructions that the operating system can schedule independently. A running Java program starts with at least one thread, the main thread, which executes main. Additional threads let work happen in parallel: one downloads data while another updates the interface, or several workers process a queue at once.

Concurrency introduces correctness risks. When two threads read and write the same variable without coordination, the final result depends on timing. That bug is called a race condition, and it is the central reason synchronization exists.

Creating Threads with Runnable

The preferred modern approach is to implement Runnable, a task that a Thread can run. Keeping the task separate from the thread object makes the code reusable with thread pools later.

class PrintTask implements Runnable {
    private String label;

    PrintTask(String label) {
        this.label = label;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 3; i++) {
            System.out.println(label + " step " + i);
        }
    }
}

public class RunnableDemo {
    public static void main(String[] args) {
        Thread first = new Thread(new PrintTask("Worker A"));
        Thread second = new Thread(new PrintTask("Worker B"));

        first.start();
        second.start();
    }
}

Call start, not run. start asks the JVM to create a new operating system thread and then invokes run on that thread. Calling run directly simply runs the code on the current thread with no concurrency.

Extending Thread

The alternative is to subclass Thread and override run. It works for simple examples, but it locks your design into one inheritance slot and couples the task to the thread, so most codebases prefer Runnable.

class CounterThread extends Thread {
    @Override
    public void run() {
        System.out.println("Counting inside " + getName());
    }
}

public class ThreadExtendDemo {
    public static void main(String[] args) {
        CounterThread worker = new CounterThread();
        worker.start();
    }
}

Thread Life Cycle

A thread moves through well known states during its life.

StateMeaning
NewCreated but start not called yet
RunnableReady to run or already running
WaitingPaused until another thread signals it
Timed waitingPaused for a fixed duration such as sleep
BlockedWaiting for a monitor lock or synchronized entry
Terminatedrun finished or ended with an error

Understanding these states helps you diagnose freezes. A thread stuck in blocked often means it waits forever for a lock held by another thread.

The Race Condition Problem

Two threads incrementing one shared counter without protection can lose updates because both may read the same old value before either writes the new one.

class UnsafeCounter {
    private int count = 0;

    void increment() {
        count = count + 1;
    }

    int getCount() {
        return count;
    }
}

Even though increment looks short, it contains read, compute, and write steps. Interleaving those steps across threads produces totals smaller than the number of increments.

Synchronized Methods

The synchronized keyword ensures only one thread at a time may execute a given method on a given object. Other threads block until the lock is released, which serializes access and preserves correctness.

class SafeCounter {
    private int count = 0;

    synchronized void increment() {
        count = count + 1;
    }

    synchronized int getCount() {
        return count;
    }
}

Synchronization trades some speed for safety. Hold locks for short durations, never perform slow input while holding one, and prefer higher level tools from the java.util.concurrent package in larger systems. Those tools, including atomic classes and executor services, build on the same locking ideas with friendlier APIs.

Daemon Threads

Threads marked as daemon run in the background and do not prevent the JVM from exiting. Non daemon threads keep the program alive until they finish. Typical uses for daemon threads include heartbeats and cache refreshers, while work you must complete should stay non daemon.

Key Takeaways

💡

  • Threads let independent tasks progress concurrently inside one process
  • Implement Runnable for tasks and pass them to Thread
  • start schedules a new thread; run alone executes on the current thread
  • Race conditions occur when threads interleave reads and writes on shared data
  • synchronized serializes access to a method and prevents lost updates

Practice Questions

  1. What is the difference between calling start and calling run on a Thread?
  2. Create two threads that print even and odd numbers up to ten and observe the interleaved output.
  3. Explain a race condition in plain language and show how synchronized prevents it.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Java Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement