使用Java 8中的线程和lambda按顺序打印数字

huangapple go评论73阅读模式
英文:

Print numbers in sequence using threads and lambdas in Java 8

问题

我在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:for(int i=0; i<10; i+=2),我会得到输出 Even thread= 0,然后程序停止执行。为什么在早期的for循环样式中,线程和lambda是如何完成这项工作的,其中递增是在条件内部而不是在循环声明行本身呢?

英文:

I came across code to print numbers in sequence using two threads in Java. Here's the code

public class ThreadPrint {
	public static boolean isOdd = false;

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

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

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

My question here is if I increment i as i+=2 in the loop itself like

for(int i=0; i&lt;10; i+=2)

I get an output as Even thread= 0 and then the program stops execution. How is this thread and lambda getting this job done in the earlier style of for loop where the incrementation is inside a condition but why not in the loop declaration line itself?

答案1

得分: 1

for (int i = 0; i <= 10;)不会增加变量i,因此作为无限循环。您的代码不是线程安全的,在两个线程之间访问isOdd时没有同步。然而,由于循环是无限的,每个线程最终都会通过if(isOdd)if(!isOdd)五次,并打印这些值。

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

英文:

for (int i = 0; i &lt;= 10;) will not increment the variable i, hence acting as an infinite loop. Your code is not thread-safe, there is no synchronization on the accessing of isOdd between the two threads. However, since the loop is infinite, each thread will eventually pass the if(isOdd) or if(!isOdd) five times and print the values.

When the increment is placed in the for loop, most of the if checks will fail as threads are not synchronized, while there are only five attempts for each thread.

huangapple
  • 本文由 发表于 2020年8月19日 01:25:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63473696.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定