Java program to print odd and even number in two seperate threads.

Java Spring Decoded
Javarevisited
Published in
2 min readJul 1, 2023

Here we are trying to print odd and even numbers in two seperate threads sequentially using the concepts of multithreading in java.

First we will create two methods , one to print odd numbers and one to print even numbers till we reach the last number .

In both the methods we will use the object level lock to awake the waiting threads to notify the other thread.

First when we enter the first method , we will check if the number is odd or even , basis on which we will print the number and increment the counter so one thread will always be waiting and one thread will be awaken by the other thread once it prints the corresponding odd/even number .

Since , we have taken the lock on the object , all the threads waiting on that object lock will be notified and hence the other thread will start executing once it gets notified by the other thread .

public class MyClass{

int count = 1;

static int N;

public void printOddNumber()
{
synchronized (this)
{
while (count < N) {


while (count % 2 == 0) {
try {
wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(count + " ");
count++;
notify();
}
}
}

public void printEvenNumber()
{
synchronized (this)
{
while (count < N) {
while (count % 2 == 1) {
try {
wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(count + " ");
count++;
notify();
}
}
}
public static void main(String[] args)
{
N = 10;
MyClass myClass = new MyClass();
Thread t1 = new Thread(new Runnable() {
public void run()
{
myClass.printEvenNumber();
}
});
Thread t2 = new Thread(new Runnable() {
public void run()
{
myClass.printOddNumber();
}
});
t1.start();
t2.start();
}
}

--

--

Java Spring Decoded
Javarevisited

All Articles related to java , spring , Backend Development and System Design.