以下简单代码的输出对我来说有点奇怪。它遗漏了在控制台上打印的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);
}
}
}发布于 2013-12-15 01:14:00
您应该在调用关机后等待executor服务完成。
executorService.shutdown();
executor.awaitTermination(30, TimeUnit.SECONDS); // Wait for the tasks to finish.
// and flush!
System.out.flush();发布于 2013-12-15 01:17:59
我怀疑创建的线程是守护进程线程,它不会阻止JVM关闭。由于线程被踢开并被遗忘,在调用shutdown之后,方法返回,然后JVM退出,因为没有其他事情可做。未完成的工作永远不会完成。
正如埃利奥特指出的那样,使用awaitTermination方法:
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#awaitTermination(long
https://stackoverflow.com/questions/20590127
复制相似问题