📌  相关文章
📜  使用Java中的两个线程按递增顺序打印偶数和奇数

📅  最后修改于: 2022-05-13 01:55:02.081000             🧑  作者: Mango

使用Java中的两个线程按递增顺序打印偶数和奇数

先决条件: 多线程

给定一个整数N,任务是编写Java程序以使用两个线程按升序打印前N个自然数。

例子:

方法:这个想法是创建两个线程,用一个线程打印偶数,用另一个线程打印奇数。以下是步骤:

  • 使用以下语法创建两个线程T1T2 ,其中T1T2分别用于打印奇数和偶数。
  • 维护一个全局计数器变量并使用以下函数启动两个线程:
  • 如果计数器在线程T1中是偶数,则等待线程T2打印该偶数。否则,打印该奇数,递增计数器并使用函数notify() 通知线程T2
  • 如果线程T2中的计数器为奇数,则等待线程T1打印该奇数。否则,打印该偶数,递增计数器并使用函数notify() 通知线程T1

下面是上述方法的实现:

Java
// 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();
    }
}


输出:
1 2 3 4 5 6 7 8 9 10


时间复杂度: O(N)
辅助空间: O(1)