How to print odd and even numbers one by one using thread ?
In this tutorial we will see how to print odd and even numbers starting from a particular number till a particular number using Threads. Below is the logic that we would be using to accomplish this:
- If number%2==1 then Odd thread will print the number and increment it else will go in the wait state.
- If number%2==0 then Even thread will print the number and increment it else will go in the wait state.
class MyRunnable implements Runnable{ public int PRINT_NUMBERS_UPTO=10; static int currentNumber=1; int remainder; static Object obj=new Object(); MyRunnable(int remainder){ this.remainder=remainder; } @Override public void run() { while (currentNumber < PRINT_NUMBERS_UPTO) { synchronized (obj) { while (currentNumber % 2 != remainder) { // wait for numbers other than remainder try { obj.wait(); Thread.sleep(3000); //some dummy process } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + " " + currentNumber); currentNumber++; obj.notifyAll(); } } } }
Call the above class from a main class:
public class Manager { public static void main(String[] args) { Thread t1=new Thread(new MyRunnable(1),"Odd"); Thread t2=new Thread(new MyRunnable(0),"Even"); t1.start(); t2.start(); } }