Java
Multithreading
Concurrency
Even and Odd
Thread Synchronization

Printing Even and Odd using two Threads in Java

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Multithreading in Java is an essential concept that allows concurrent execution of two or more threads, providing a way to maximize utilization of CPU resources. In this article, we explore an intriguing use-case of multithreading: printing even and odd numbers using two separate threads. This challenge not only illustrates thread synchronization but also deepens understanding of thread communication.

The Problem

The task is to print even and odd numbers in sequence using two threads. The even numbers should be printed by one thread, and the odd numbers by another in a coordinated manner, ensuring they alternate correctly.

Thread Basics

What is a Thread?

A thread is a lightweight subprocess, a smallest unit of processing. In Java, every thread is an instance of java.lang.Thread class or java.lang.Runnable interface. Threads in Java can be created in two ways:

  1. By extending the Thread class.
  2. By implementing the Runnable interface.

Thread States

Threads in Java can exist in several states:

  • New: A thread that has been created but not yet started.
  • Runnable: A thread that is ready to run and waiting for CPU time.
  • Blocked/Waiting: A thread that is waiting for some monitor lock or other threads to execute a specific action.
  • Timed Waiting: A thread that is waiting for a specified waiting time, such as sleep() , join() , etc.
  • Terminated: A thread that has exited.

Synchronization - The Key Concept

To ensure accurate alternation between even and odd printing threads, we need thread synchronization, a process that allows controlling the access of multiple threads to shared resources.

synchronized

Keyword

In Java, synchronization is achieved using the synchronized keyword, which can be used in two ways:

  1. Synchronized Method: Entire methods can be synchronized using this keyword.
  2. Synchronized Block: Critical sections of code can be enclosed within a synchronized block to provide more fine-grained control.

Example

Below is a complete Java code example illustrating how two threads can be utilized to print even and odd numbers up to a specified limit.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.