3

下面的代码检查ExecutorCompletionServicefrom Java Concurrencyframework 的使用情况(正在使用的 IDE 是 Netbeans)。

但程序不会终止。为什么?

代码:

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();
    }
}
4

1 回答 1

6

线程池中的线程在main完成后将继续运行。这就是JVM不会关闭的原因。您需要使用守护线程,或明确关闭池。

这是一个例子:

ExecutorService ex = Executors.newCachedThreadPool();
// do all your submission work here
ex.shutdown();
于 2014-03-21T11:10:19.400 回答