Printing numbers in sequence from alternating threads

This article demonstrates printing numbers in sequence from alternating threads. This is a very popular multi-threading question asked in Java technical interviews.

 

The Problem Statement

Print the natural sequence of integers starting from 1 from a set of 3 (or more) threads that take turns in a round robin fashion; such that, thread 1 prints 1, thread 2 prints 2, thread 3 prints 3 and then thread 1 prints 4 and so on.

 

The Solution

I have seen people writing crazy and complex logic to switch between threads. In this article, we present a more subtle and elegant way to achieve the objective.

First, we define a worker holding a blocking queue. The workers waits on the queue until it receives a number in it. It prints the number it receives, increments it and passes it on to the next worker in the chain.

Then, we create the required number of workers instances and tie them together to create a circular chain. Then, assign each worker a separate thread and set them off.

Each worker waits until it receives a number and then prints the number, increments it and passes the number to next worker in the chain. The next worker repeats the process and so on. As a result, the numbers are printed sequentially from different threads in the chain.

 

The Worker

 

The Main

 

The Output

 


 

1
Leave a Reply

avatar
300
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
randomGuy Recent comment authors
  Subscribe  
newest oldest
Notify of
randomGuy
Guest
randomGuy

A very nice approach.