Tuesday, February 13, 2018

Printing Numbers in Sequence from alternating Threads in java

This is one of the most asked multi threading interview question we you need to write the program in which there will be 2 thread one will print even number and second will print odd number but we need to write the program in which the output will be the sequential.

Problem Statement
Write a multi threaded program to print continues number from 1 to 100 or 1 to 10(assume we will use only 2 threads).

If You don’t know the basics of Multithreading you can see my previous posts



  • To Solve the problem we need to think in a way that there will be 2 threads , one will print even number and second will print odd number.
  • As The thread sequence is not defined we need to think about the sequencing of the thread , as Thread1 thread2 thread1 thread2 thread1 
    • Above will be the sequence in which we need to print the thread.
  • Now to achieve this sequence we need to use Wait & Notify Mechanism. If you don’t know about the Wait and Notify in java see my previou post – Wait and Notify in Threading
  • So we will Create one Class in which we will be having one Boolean value which maintain the current sequence is either odd or even.
  • This class called as counter will be used for lock over and the condition will be checked as if count.isEven = false thread2 (which is odd print thread) will take the lock
  • Count.isEven =true thread1 (which is even print thread) will take the lock.
  • After print the value the current thread will notify() other thread who is waiting for lock but before release the thread will change the count.isEven value to be negation of current.
In this way we can achieve the solution.
Programmatic Solution.

  • Here we have created 2 classes one is ContiniousPrintDemo second is Counter.
  • The ContiniousPrintDemo (will say Main class in future) is the Main Class where we have created 2 threads one will print even number and second will print odd number.
  • Counter class is used for Locking and checking the current value of the Count.
    • If the current value of count is even thread 1 will take lock , if count value will be odd thread 2 will take the lock.
This way we will be able to solve this problem 

If you have any problem or issue fell free to leave us a comment , will be happy to help you 

Thanks for reading


Post a Comment