gpt4 book ai didi

java System.out 丢失

转载 作者:行者123 更新时间:2023-11-30 04:06:41 28 4
gpt4 key购买 nike

以下简单代码的输出对我来说有点奇怪。它错过了在控制台上打印的 0 到 100 之间的一些数字。

谁能解释一下为什么省略打印?我对并发编程完全陌生。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.Test;


public class SimpleTest {

@Test
public void testSimple() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(10);

for(int i = 0; i <= 100; i++) {
executorService.execute(new SimpleRunnable(i));
}

executorService.shutdown();
}

}

class SimpleRunnable implements Runnable {

int i;

public SimpleRunnable(int i) {
this.i = i;
}

public void run() {
synchronized(System.out) {
System.out.println(i);
}
}

}

最佳答案

调用 shutdown 后应等待执行器服务完成

executorService.shutdown();
executor.awaitTermination(30, TimeUnit.SECONDS); // Wait for the tasks to finish.
// and flush!
System.out.flush();

关于java System.out 丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20590127/

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