Print Even Odd Number Two Threads Java

Print Even Odd Number Two Threads Java

Now a days this question is very popular among the companies during first round screening process to check candidate programming ability. Question detail is below:

Please implement a program that launches two threads.The fist will increment a global int by one when it is even, the second will increment the same global int by one when it is odd. the program should accept a parameter to indicate the value of the global int to terminate execution . please provide two implementations, one using standard locking mechanism and the other using lock-less techniques.

Below sample java program where lock has been created on class level, two separate thread is created where first thread will increment the number if its even and its not event then he will notify second thread and wait to get his chance again. Second there will increment the number if it’s odd if not then he will notify first thread vice-versa.

  • TwoThreadEvenOddIncrement.java using lock:

  • Output:

Print Even Odd Number Two Threads Java

  • PrintEvenOddWithoutLock.java: Without using lock

  • Output:

Print Even Odd Number Two Threads Java

Reference:

Leave a Reply

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