[英]Why Java program not terminating
The code below checks the usage of ExecutorCompletionService
from Java Concurrency
framework (the IDE being used is Netbeans). 下面的代码检查Java Concurrency
框架(使用的IDE是Netbeans)中ExecutorCompletionService
的使用情况。
But the program doesn't terminate. 但是程序不会终止。 Why? 为什么?
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;
public class TestFuture {
public static void main(String... args) throws InterruptedException, ExecutionException {
Executor ex = Executors.newCachedThreadPool();
CompletionService<Long> cs = new ExecutorCompletionService<Long>(ex);
cs.submit(new Worker());
cs.submit(new Worker());
cs.submit(new Worker());
for (int i = 0; i < 3; i++) {
long l = cs.take().get();
//utilize the result
System.out.println(l);
}
}
}
class Worker implements Callable {
@Override
public Long call() throws Exception {
//do some task and return back
return System.currentTimeMillis();
}
}
Threads in thread pool will keep running when main
is finished. main
完成后,线程池中的线程将继续运行。 That's why JVM won't shut down. 这就是为什么JVM不会关闭的原因。 You need to either use daemon-threads, or shutdown the pool explicitly. 您需要使用守护程序线程,或显式关闭池。
Here's an example: 这是一个例子:
ExecutorService ex = Executors.newCachedThreadPool();
// do all your submission work here
ex.shutdown();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.