Print 1,2,3 using three threads Java

Before jumping into this problem, I recommend to go through printing odd, even numbers using 2 threads post. In this problem, We used a single Boolean object which has three values — true, false, null.

When true we will print 1 while other 2 threads will be waiting for their turn. When first thread is done with printing, it will call notifyAll() on the object and gives the access to second thread with the help of isTurn variable.

Then, the second thread will print 2 while other threads are waiting. Then, second thread will call notifyAll(). The variable isTurn is deciding which thread should get access to the object. Now, the access will be passed to third thread and other threads will be waiting.

The same logic of passing the control from first thread to second thread, from second thread to third thread and from third thread to first thread again continues till the loop ends.

The final Output will be like below. 

Java 1,2,3 multithreading output



Post a Comment