Print even and odd numbers in increasing order using two threads in Java

Prerequisite: Multithreading

Given an integer N, the task is to write Java Program to print the first N natural numbers in increasing order using two threads.

Examples:

Input: N = 10
Output: 1 2 3 4 5 6 7 8 9 10

Input: N = 18
Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18



Approach: The idea is to create two threads and print even numbers with one thread and odd numbers with another thread. Below are the steps:

  • Create two threads T1 and T2 using the below syntax, where T1 and T2 are used to print odd and even numbers respectively.

    Thread T1 = new Thread(new Runnable() {
               public void run() { mt.printEvenNumber(); }
    });

    Thread T2 = new Thread(new Runnable() {
               public void run() { mt.printOddNumber(); }
    });

    where,
    printOddNumber() is used to print all the odd numbers till N,
    printEvenNumber() is used to print all the even numbers till N.

  • Maintain a global counter variable and start both threads using the below function:

    T1.start();
    T2.start();

  • If the counter is even in the Thread T1, then wait for the thread T2 to print that even number. Otherwise, print that odd number, increment the counter and notify to the Thread T2 using the function notify().
  • If the counter is odd in the Thread T2, then wait for the thread T1 to print that even number. Otherwise, print that even number, increment the counter and notify the Thread T1 using the function notify().

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
  
public class GFG {
  
    // Starting counter
    int counter = 1;
  
    static int N;
  
    // Function to print odd numbers
    public void printOddNumber()
    {
        synchronized (this)
        {
            // Print number till the N
            while (counter < N) {
  
                // If count is even then print
                while (counter % 2 == 0) {
  
                    // Exception handle
                    try {
                        wait();
                    }
                    catch (
                        InterruptedException e) {
                        e.printStackTrace();
                    }
                }
  
                // Print the number
                System.out.print(counter + " ");
  
                // Increment counter
                counter++;
  
                // Notify to second thread
                notify();
            }
        }
    }
  
    // Function to print even numbers
    public void printEvenNumber()
    {
        synchronized (this)
        {
            // Print number till the N
            while (counter < N) {
  
                // If count is odd then print
                while (counter % 2 == 1) {
  
                    // Exception handle
                    try {
                        wait();
                    }
                    catch (
                        InterruptedException e) {
                        e.printStackTrace();
                    }
                }
  
                // Print the number
                System.out.print(
                    counter + " ");
  
                // Increment counter
                counter++;
  
                // Notify to 2nd thread
                notify();
            }
        }
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Given Number N
        N = 10;
  
        // Create an object of class
        GFG mt = new GFG();
  
        // Create thread t1
        Thread t1 = new Thread(new Runnable() {
            public void run()
            {
                mt.printEvenNumber();
            }
        });
  
        // Create thread t2
        Thread t2 = new Thread(new Runnable() {
            public void run()
            {
                mt.printOddNumber();
            }
        });
  
        // Start both threads
        t1.start();
        t2.start();
    }
}

chevron_right


Output:

1 2 3 4 5 6 7 8 9 10


Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Strategy Path planning and Destination matters in success No need to worry about in between temporary failures

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.