英文:
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 = () -> {
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();
}
}
My question here is if I increment i as i+=2 in the loop itself like
for(int i=0; i<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 <= 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论