Print Numbers Sequentially Using Three Threads in Java

This post shows how you can write a program in Java to print numbers in sequence using three threads. If there are three threads T1, T2, T3 then numbers should be printed alternatively by these threads in the following manner-

T1- 1
T2- 2
T3- 3
T1- 4
T2- 5
T3- 6
..
..
..

Printing numbers using 3 threads – Java program

In the program each thread is assigned a number (0, 1 and 2 respectively). Before thread prints a number, each number is divided by 3 and the thread which has an assigned number equal to the remainder of this division is eligible to print the number.

For example-

if number % 3 ==0 Then T1 prints the number
if number % 3 ==1 Then T2 prints the number
if number % 3 ==2 Then T3 prints the number

This program for printing numbers in sequence using threads can be written using only synchronized keyword or it can be written using wait, notify, notifyAll methods for inter thread communication.

Printing numbers using 3 threads and synchronized

Output

Printing numbers using 3 threads and wait notify

Java program using wait notify is very similar to the example above except that there is a condition for wait now (while(number % 3 != threadNumber)). Unless the assigned thread number is not equal to the remainder of the number division by 3, thread is made to wait.

Only when the assigned thread number is equal to the remainder of the number division thread prints the number and notifies other waiting threads so that one of them can enter the synchronized block.

Another interesting thing in the code is this condition- while (number < PrintNumbers.MAX_NUMBERS – 2). Why check for two less than the required number? It is because loop will anyway run for all the three threads and for value 8 itself one thread will increment it to 9 and another to 10.

Output

That’s all for the topic Print Numbers Sequentially Using Three Threads in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

  • How to List All The Files in a Directory in Java
  • Method Reference in Java
  • Volatile Keyword in Java
  • final Vs finally Vs finalize in Java
  • Static Keyword in Java
  • HDFS Data Flow – File Read And Write in HDFS
  • Leave a Reply

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

    This site uses Akismet to reduce spam. Learn how your comment data is processed.