Print even odd numbers using two threads in java

In this post, we will see how to print even and odd numbers using two threads in java.This is generally asked in core java interview to test multithreading skills.

Problem

We need to print odd number with one thread and even number using another thread in java.
Example

Thread 1 –> 1
Thread 2 –> 2
Thread 1 –> 3
Thread 2 –> 4
Thread 1 –> 5
Thread 2 –> 6
Thread 1 –> 7
Thread 2 –> 8
Thread 1 –> 9
Thread 2 –> 10

Here is simple program which can print about sequence.

Create main program as below to execute.

Output

Thread 1 –> 1
Thread 2 –> 2
Thread 1 –> 3
Thread 2 –> 4
Thread 1 –> 5
Thread 2 –> 6
Thread 1 –> 7
Thread 2 –> 8
Thread 1 –> 9
Thread 2 –> 10
Thread 1 –> 11
Thread 2 –> 12
Thread 1 –> 13
Thread 2 –> 14
Thread 1 –> 15
Thread 2 –> 16
Thread 1 –> 17
Thread 2 –> 18
Thread 1 –> 19
Thread 2 –> 20

Explanation

  • If num%2!=1, then thread 1 will go into wait state, otherwise it will print the num.
  • If num%2!=0, then thread 2 will go into wait state, otherwise it will print the num.
  • Please note that we have taken class level lock here, because we are using two different runnable object to print the sequence.

Leave a Reply

Your email address will not be published. Required fields are marked *