3

以下のコードは、ExecutorCompletionServicefromJava Concurrencyフレームワーク (使用されている 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 に答える