Java program to Print numbers in sequence using 3 Threads

By | May 29, 2020

In this post, we will learn  How to write a java program to Print numbers in sequence using 3 Threads.

Numbers have to print in below order by all 3 Threads::

Thread-1   Thread-2   Thread-3
1                    2                        3
4                   5                         6
7                  8                          9
10               11                         12

————————————–

 

NumbersGenerator.java is used by all three threads to generate numbers in Sequence

 

Each thread call method numbersGenerator.printNumbers(result) to generate numbers in sequence

Client program SequenceNumberGeneratorTest.java

If you run client program SequenceNumberGeneratorTest.java then this will generate below output:

Thread-1 1
Thread-2 2
Thread-3 3
Thread-1 4
Thread-2 5
Thread-3 6
Thread-1 7
Thread-2 8
Thread-3 9
Thread-1 10

 

You May Also Like:

How to convert number to words in java
How to swap two numbers with or without temporary variable in java
Java Program to Swap two numbers using Bitwise XOR Operator?
How to reverse a number in Java
How to check Armstrong number java program
Java program to find factorial of a number
Java Program to Calculate the Power of a Number
Check whether a number is prime or not

That’s all about Java program to Print numbers in sequence using 3 Threads?
If you have any feedback or suggestion please feel free to drop in below comment box.

 

 

2 thoughts on “Java program to Print numbers in sequence using 3 Threads

  1. Sreekar

    Hii kishan,
    Query re: Java program to Print numbers in sequence using 3 Threads
    I’ve used the same code to print 40 numbers using 5 threads, but threads are printing the numbers greater than total numbers to be printed.

    pls find the below output.
    Thread-1—1
    Thread-2—2
    Thread-3—3
    Thread-4—4
    Thread-5—5
    Thread-1—6
    Thread-2—7
    Thread-3—8
    Thread-4—9
    Thread-5—10
    Thread-1—11
    Thread-2—12
    Thread-3—13
    Thread-4—14
    Thread-5—15
    Thread-1—16
    Thread-2—17
    Thread-3—18
    Thread-4—19
    Thread-5—20
    Thread-1—21
    Thread-2—22
    Thread-3—23
    Thread-4—24
    Thread-5—25
    Thread-1—26
    Thread-2—27
    Thread-3—28
    Thread-4—29
    Thread-5—30
    Thread-1—31
    Thread-2—32
    Thread-3—33
    Thread-4—34
    Thread-5—35
    Thread-1—36
    Thread-2—37
    Thread-3—38
    Thread-4—39
    Thread-5—40
    Thread-1—41
    Thread-2—42

    It would be great if you let me know where to alter the code

    Reply
  2. javac

    Replace
    while (number < totalNumbersInSequence-1)
    with
    while (number < totalNumbersInSequence – numOfThreads +1)

    The reason is when the threads will come to runnable state from wait state, the last part [below lines of wait() call] of printNumbers() method would be executed.

    Reply

Leave a Reply

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