completionservice:如何杀死所有线程并通过5秒返回结果?

gis*_*ild 1 java concurrency multithreading

我对CompletionService有一些问题.我的任务:对于大约300个html页面并行解析, 我需要等待所有结果仅持续5秒,然后 - 将结果返回到主代码.我决定使用CompletionService + Callable. 问题是如何停止所有线程,这些线程是由CompletionService引起的并返回那些被成功解析的结果?在这段代码中删除了printlines,但我可以说5秒就足够了(有很好的结果,但程序在所有线程完成时都会等待).我的代码执行了大约2分钟.

我的通话代码:

Collection<Callable<HCard>> solvers = new ArrayList<Callable<HCard>>();
for (final String currentUrl : allUrls) {
    solvers.add(new Callable<HCard>() {
        public HCard call() throws ParserException {
            HCard hCard = HCardParser.parseOne(currentUrl);                      
            if (hCard != null) {
                return hCard;
            } else {
                return null;
            }
        }
    });
}
ExecutorService execService = Executors.newCachedThreadPool();
Helper helper = new Helper();
List<HCard> result = helper.solve(execService, solvers);
//then i do smth with result list
Run Code Online (Sandbox Code Playgroud)

我叫的代码:

public class Helper {
List<HCard> solve(Executor e, Collection<Callable<HCard>> solvers) throws InterruptedException {
    CompletionService<HCard> cs = new ExecutorCompletionService<HCard>(e);
    int n = solvers.size();

    Future<HCard> future = null;
    HCard hCard = null;
    ArrayList<HCard> result = new ArrayList<HCard>();

    for (Callable<HCard> s : solvers) {
        cs.submit(s);
    }
    for (int i = 0; i < n; ++i) {
        try {
            future = cs.take();
            hCard = future.get();
            if (hCard != null) {
                result.add(hCard);
            }
        } catch (ExecutionException e1) {
            future.cancel(true);
        }
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

我试图使用:

  • awaitTermination(5000,TimeUnit.MILLISECONDS)
  • future.cancel(真)
  • execService.shutdownNow()
  • future.get(5000,TimeUnit.MILLISECONDS);
  • TimeOutException:我不能得到TimeOutException.

请帮我解释一下我的代码背景.
提前致谢!

Kev*_*vin 6

您需要确保您提交的任务正确地响应中断,即,它们检查Thread.isInterrupted()或以其他方式被视为"可中断".

我不确定你需要一个完成服务.

ExecutorService service = ...

// Submit all your tasks
for (Task t : tasks) {
    service.submit(t);
}

service.shutdown();

// Wait for termination
boolean success = service.awaitTermination(5, TimeUnit.SECONDS);
if (!success) {
    // awaitTermination timed out, interrupt everyone
    service.shutdownNow();
}
Run Code Online (Sandbox Code Playgroud)

此时,如果您的Task对象没有响应中断,则无法执行任何操作