gpt4 book ai didi

java - 主线程随机没有结束(试图在并发线程中求和自然数)

转载 作者:行者123 更新时间:2023-11-30 06:12:47 24 4
gpt4 key购买 nike

<分区>

我有以下代码来计算从 1 到 5000 的自然数之和。这是练习并发的简单练习。

public static void main(String[] args) throws InterruptedException {
final int[] threadNb = new int[] {5};
final Integer[] result = new Integer[1];
result[0] = 0;
List<Thread> threads = new LinkedList<>();
IntStream.range(0, threadNb[0]).forEach(e -> {
threads.add(new Thread(() -> {
int sum = 0;
int idx = e * 1000 + 1;
while (!Thread.interrupted()) {
if (idx <= (e + 1) * 1000) {
sum += idx++;
} else {
synchronized(result) {
result[0] += sum;
System.err.println("sum found (job " + e + "); sum=" + sum + "; result[0]=" + result[0] + "; idx=" + idx);
Thread.currentThread().interrupt();
}
}
}
synchronized(result) {
System.err.println("Job " + e + " done. threadNb = " + threadNb[0]);
threadNb[0]--;
System.err.println("threadNb = " + threadNb[0]);
}
}));
});
threads.forEach(Thread::start);
//noinspection StatementWithEmptyBody
while(threadNb[0] > 0);
System.out.println("begin result");
System.out.println(result[0]);
System.out.println("end result");
}

有时,当我运行代码时,不会显示最后 3 个 System.out.println()。如果我在 while(threadNb[0] > 0) 中放置一个语句,就像另一个 System.out.println() 一样,我的问题就不会再发生了。

谁能给我解释一下这种行为?

在此先感谢您的帮助

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com