第五章 如何使用java中的线程打印偶数和奇数


你有两个线程。您需要使用一个线程打印奇数,使用另一个线程打印偶数。您需要以自然顺序打印最多 MAX。 例如: 如果 MAX 为 10,则需要打印:

1 2 3 4 5 6 7 8 9 10

所以 1 3 5 7 9 将由奇数线程打印 2 4 6 8 10 将由偶数线程打印。

解决方案 1

我们将使用等待和通知来解决如何在java中使用线程打印偶数和奇数。

  • 使用一个名为 boolean odd的变量。如果要打印奇数,它的值应该为真,反之亦然。
  • 创建两个方法printOdd()printEven()一个打印奇数,另一个打印偶数。
  • 创建两个线程,t2用于奇数和t1偶数。
  • t1将调用printEven()方法并将同时t2调用printOdd()方法。
  • 如果 boolean在方法中odd为真,将等待。printEven()``t1
  • 如果 boolean在方法中odd为 false ,将等待。printOdd()``t2

使用java中的线程打印偶数和奇数

package org.arpit.java2blog;

public class OddEvenPrintMain {

    boolean odd;
    int count = 1;
    int MAX = 20;

    public void printOdd() {
        synchronized (this) {
            while (count < MAX) {
                System.out.println("Checking odd loop");

                while (!odd) {
                    try {
                        System.out.println("Odd waiting : " + count);
                        wait();
                        System.out.println("Notified odd :" + count);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                System.out.println("Odd Thread :" + count);
                count++;
                odd = false;
                notify();
            }
        }
    }

    public void printEven() {

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        synchronized (this) {
            while (count < MAX) {
                System.out.println("Checking even loop");

                while (odd) {
                    try {
                        System.out.println("Even waiting: " + count);
                        wait();
                        System.out.println("Notified even:" + count);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("Even thread :" + count);
                count++;
                odd = true;
                notify();

            }
        }
    }

    public static void main(String[] args) {
    OddEvenPrintMain oep = new OddEvenPrintMain();
        oep.odd = true;
        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                oep.printEven();

            }
        });
        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                oep.printOdd();

            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

当你运行上面的程序时,你会得到下面的输出:

Checking odd loop
Odd Thread :1
Checking odd loop
Odd waiting : 2
Checking even loop
Even thread :2
Checking even loop
Even waiting: 3
Notified odd :3
Odd Thread :3
Checking odd loop
Odd waiting : 4
Notified even:4
Even thread :4
Checking even loop
Even waiting: 5
Notified odd :5
Odd Thread :5
Checking odd loop
Odd waiting : 6
Notified even:6
Even thread :6
Checking even loop
Even waiting: 7
Notified odd :7
Odd Thread :7
Checking odd loop
Odd waiting : 8
Notified even:8
Even thread :8
Checking even loop
Even waiting: 9
Notified odd :9
Odd Thread :9
Checking odd loop
Odd waiting : 10
Notified even:10
Even thread :10
Checking even loop
Even waiting: 11
Notified odd :11
Odd Thread :11
Checking odd loop
Odd waiting : 12
Notified even:12
Even thread :12
Checking even loop
Even waiting: 13
Notified odd :13
Odd Thread :13
Checking odd loop
Odd waiting : 14
Notified even:14
Even thread :14
Checking even loop
Even waiting: 15
Notified odd :15
Odd Thread :15
Checking odd loop
Odd waiting : 16
Notified even:16
Even thread :16
Checking even loop
Even waiting: 17
Notified odd :17
Odd Thread :17
Checking odd loop
Odd waiting : 18
Notified even:18
Even thread :18
Checking even loop
Even waiting: 19
Notified odd :19
Odd Thread :19
Notified even:20
Even thread :20

如果你观察输出,你应该能够理解上面的程序。

让我试着解释一下前几行: 检查奇数循环: 检查方法奇数线程t2中的 while 条件:1:打印计数,将其加一并进行检查奇数循环:检查方法奇数等待中的 while 条件:2:因为 现在,将等待并释放检查偶数循环:检查方法偶数线程中的 while 条件:2:打印,将其递增一并进行检查偶数循环:检查方法中的 while 条件偶数等待:3:从现在开始,将等待并释放锁printOdd() t2``odd=false printOdd() odd=false``t2``lock t1``printEven() t1``count``odd=true t1``printEven() odd=true``t1 通知奇数:3:由于我们notify()在打印的时候已经调用了Even thread 2,所以它会通知t2

解决方案 2:使用余数

您可以在这里使用余数的概念。

  • 如果number%2==1thenOdd将打印数字并增加它,否则将进入该wait状态。
  • 如果number%2==0然后 Even 将打印数字并增加它,否则将进入该wait状态。

让我们在示例的帮助下进行检查。

创建一个名为OddEvenRunnable并实现Runnable接口的类。

Create a class named <code>OddEvenRunnable</code>. It will implement Runnable interface.

public class OddEvenRunnable implements Runnable{

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

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

    @Override
    public void run() {
        while (number < PRINT_NUMBERS_UPTO) {
            synchronized (lock) {
                while (number % 2 != 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();
            }
        }
    }
}

创建名为“PrintOddEvenMain”的主类

public class PrintOddEvenMain {
    public static void main(String[] args) {

        OddEvenRunnable oddRunnable=new OddEvenRunnable(1);
        OddEvenRunnable evenRunnable=new OddEvenRunnable(0);

        Thread t1=new Thread(oddRunnable,"Odd");
        Thread t2=new Thread(evenRunnable,"Even");

        t1.start();
        t2.start();

    }
}

当你运行上面的程序时,你会得到下面的输出

Odd 1
Even 2
Odd 3
Even 4
Odd 5
Even 6
Odd 7
Even 8
Odd 9
Even 10

这完全是关于使用 java 中的线程打印偶数和奇数。如果解释不是很清楚,请发表评论。


原文链接:https://codingdict.com/