[英]java System.out missing out
以下简单代码的输出对我来说有点奇怪。 它会错过一些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();
我怀疑创建的线程是守护程序线程,它们不会阻止JVM关闭。 由于线程已启动并被忘记,因此在调用shutdown
,该方法将返回,然后JVM退出,因为没有其他事情可做。 未完成的工作永远不会完成。
正如Elliot指出的那样,请使用awaitTermination方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.