【发布时间】:2023-04-09 15:05:01
【问题描述】:
我遇到了使用 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 循环样式中完成这项工作,其中增量在条件内,但为什么不在循环声明行本身?
【问题讨论】:
-
这称为竞争条件:尝试从
10增加到100000。 -
@MAnouti 即使我达到 10000 也可以正常工作。为什么当我以不同的方式递增时它的行为会有所不同(一个在循环声明行中,另一个在循环中的条件中)
标签: java multithreading java-8 concurrency java-threads