Problem

You are given two threads. You need to print odd numbers using one thread and even numbers using another thread.You need to print in natural order up to MAX.For example:
If MAX is 10, you need to print:

1 2 3 4 5 6 7 8 9 10

So 1 3 5 7 9 will be printed by odd thread
2 4 6 8 10 will be printed by even thread.

Solution 1

We will use wait and notify to solve how to print even and odd numbers using threads in java.

Use a variable called boolean odd. If you want to print odd number, it’s value should be true and vice versa for even number.

Create two methods(printOdd and printEven), one will print odd numbers and other will print even numbers.

If you observe output, you should be able to understand above program.

Let me try to explain first few lines:Checking odd loop : t2 Checks for while condition in printOdd methodOdd Thread :1 : t2 Prints the count ,increment it by one and make odd =falseChecking odd loop : Checks for while condition in printOdd methodOdd waiting : 2: Since odd=false now, t2 will wait and releases the lockChecking even loop: t1 checks for while condition in printEven methodEven thread :2 : t1 prints the count,increment it by one and make odd =trueChecking even loop: t1 checks for while condition in printEven methodEven waiting: 3: Since odd=true now, t1 will wait and releases the lockNotified odd :3 : Since we have called notify when we were printing “Even thread 2”, it will notify t2.

All other steps will follow.

Solution 2: Using remainder

You can use concept of remainder here.

If number%2==1 then Odd will print the number and increment it else will go in the wait state.

If number%2==0 then Even will print the number and increment it else will go in the wait state.

Let’s check with the help of example.

Create a class named “OddEvenRunnable” and implement Runnable interface.