在Java 8中使用线程和lambda依次打印数字

问题描述

我遇到了使用Java中的两个线程按顺序打印数字的代码。这是代码

public class ThreadPrint {
    public static boolean isOdd = false;

    public static void main(String[] args) throws InterruptedException {
        Runnable even = () -> {
            for (int i = 0; i <= 10;)
                if (!isOdd) {
                    System.out.println("Even thread = " + i);
                    i = i + 2;
                    isOdd = !isOdd;
                }
        };
        Runnable odd = () -> {
            for (int i = 1; i <= 10;)
                if (isOdd) {
                    System.out.println("odd thread = " + i);
                    i = i + 2;
                    isOdd = !isOdd;
                }
        };

        Thread e = new Thread(even);
        Thread o = new Thread(odd);

        e.start();
        o.start();
    }
}

我的问题是,是否像循环一样将i递增为i + = 2

for(int i=0; i<10; i+=2)

我得到的输出 Even thread = 0 ,然后程序停止执行。该线程和lambda如何在for循环的早期样式中完成此工作,其中递增在条件内,但为什么不在循环声明行本身中呢?

解决方法

for (int i = 0; i <= 10;)不会使变量i递增,因此起着无限循环的作用。您的代码不是线程安全的,两个线程之间对isOdd的访问没有同步。但是,由于循环是 infinite ,每个线程最终将通过if(isOdd)if(!isOdd)五次并打印值。

将增量放在for循环中时,大多数if检查将由于线程不同步而失败,而每个线程只有五次尝试。