Sitelet https://java2blog.com/print-sequence-3-threads-java/

Print Numbers Using Multiple Threads in Java

Print sequence using 3 threads in java

In this post, we will see how to print numbers using multiple threads in java.It is similar to printing odd-even numbers using two threads in java.

Problem

You are given 3 threads. You need to print sequence using these 3 threads.You need to print in natural order up to MAX.

For example:
Let’s say you have 3 threads. T1,T2 and T3.
If MAX is 10, you need to print:

T1 1
T2 2
T3 3
T1 4
T2 5
T3 6
T1 7
T2 8
T3 9
T1 10

Solution

We will use concept of remainder here.

  • If number%3==1 then T1 will print the number and increment it else will go in the wait state.
  • If number%3==2 then T2 will print the number and increment it else will go in the wait state.
  • If number%3==0 then T3 will print the number and increment it else will go in the wait state.

Let me provide simple program for it.
Let’s create a class named "PrintSequenceRunnable" which will implement the Runnable interface.

public class PrintSequenceRunnable implements Runnable{

    public int PRINT_NUMBERS_UPTO=10;
    static int  number=1;
    int remainder;
    static Object lock=new Object();

    PrintSequenceRunnable(int remainder)
    {
        this.remainder=remainder;
    }

    @Override
    public void run() {
        while (number < PRINT_NUMBERS_UPTO-1) {
            synchronized (lock) {
                while (number % 3 != remainder) { // wait for numbers other than remainder
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + " " + number);
                number++;
                lock.notifyAll();
            }
        }
    }
}

Let’s create a class named "PrintThreadsSequentiallyMain" which will implement the Runnable interface.

public class PrintThreadsSequentiallyMain {

    public static void main(String[] args) {

        PrintSequenceRunnable runnable1=new PrintSequenceRunnable(1);
        PrintSequenceRunnable runnable2=new PrintSequenceRunnable(2);
        PrintSequenceRunnable runnable3=new PrintSequenceRunnable(0);

        Thread t1=new Thread(runnable1,"T1");
        Thread t2=new Thread(runnable2,"T2");
        Thread t3=new Thread(runnable3,"T3");

        t1.start();
        t2.start();
        t3.start();   
    }
}

When you run above program, you will get below output.

T1 1
T2 2
T3 3
T1 4
T2 5
T3 6
T1 7
T2 8
T3 9
T1 10

That’s all about printing numbers using multiple threads in java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Comments

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.