如何调整这3个线程的控制流?

// Task 1 -- the main thread

        SimilarityResponse w2vResponse = questionClassifier.compute(questionInfo);


        // Task 2

        String sku = questionInfo.getSku();

        String question = questionInfo.getQuestion();

        Callable<ResponseList> dssmTask = () -> this.dssmCompute(sku, question);

        Future<ResponseList> dssmService = executorService.submit(dssmTask);

        ResponseList dssmResponse;

        try {

            LOGGER.info("start dssm ... {} ", question);

            dssmResponse = dssmService.get(Parameters.getParserTimeLimit(), TimeUnit.MILLISECONDS);

            LOGGER.info("dssmResponse ... {} ", dssmResponse);

        } catch (ExecutionException | InterruptedException e) {

            LOGGER.warn("ExecutionException | InterruptedException");

            e.printStackTrace();

        } catch (TimeoutException te) {

            dssmService.cancel(true);

            LOGGER.warn("DSSM time out for {} {}", sku, question);

        }


        // Task 3

        Callable<ResponseList> stsTask = () -> this.stsCompute(sku, question);

        Future<ResponseList> stsService = executorService.submit(stsTask);

        ResponseList stsResponse;

        try {

            LOGGER.info("start sts ... {} ", question);

            stsResponse = stsService.get(Parameters.getParserTimeLimit(), TimeUnit.MILLISECONDS);

            LOGGER.info("stsResponse ... {} ", stsResponse);

        } catch (ExecutionException | InterruptedException e) {

            LOGGER.warn("ExecutionException | InterruptedException");

            e.printStackTrace();

        } catch (TimeoutException te) {

            stsService.cancel(true);

            LOGGER.warn("STS time out for {} {}", sku, question);

        }


        // Last step == do something for above

        SimilarityResponse ensemble = new SimilarityResponse();

        return ensemble;

在执行最后一步之前,如何确保任务 1-3 已经完成?当前代码似乎是先完成Task 1,然后直接返回。


Helenr
浏览 191回答 1
1回答

桃花长相依

您应该使用 CountDownLatch。在您的主线程中创建它的实例并将此实例传递给您的任务(Callables)。然后当任务完成时调用latch.countDown()。在代码的最后一步调用 latch.await() 以等待每个任务完成。它看起来像这样(如果你的 callables 是作为 lambdas 创建的):final CountDownLatch latch = new CountDownLatch(3);for(int x = 0; x < 3; x++) {&nbsp; &nbsp; service.submit( () -> {&nbsp; &nbsp; &nbsp; &nbsp; // do something&nbsp; &nbsp; &nbsp; &nbsp; latch.countDown();&nbsp; &nbsp; });}// in the end wait for tasks to finishlatch.await();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java