代码之家  ›  专栏  ›  技术社区  ›  user697911

我需要用主线程控制这两个线程的执行吗?

  •  1
  • user697911  · 技术社区  · 7 年前
    void process(String question){
    
                        Callable<ResponseList> callable1 = () -> this.stsCompute question);
                        Future<ResponseList>task1 = executorService.submit(callable1);
    
                        Callable<ResponseList> callable2 = () -> this.dssmCompute(question);
                        Future<ResponseList>task2 = executorService.submit(callable2);
    
                        try{
                            ResponseList stsResponse = task1.get();
                            ResponseList dssmResponse = task2.get();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
    
                        // Do I need to wait until the first 2 threads complete?
                        processResponse(stsResponse, dssmResponse);
    }
    

    在这个“process”方法中,我有两个额外的线程'callable1'&'callable2'以同时执行。我想确保只有当这两个任务完成时,才能开始执行主线程“processResponse()”中的方法。

    在这种情况下,我是否需要添加任何额外的控件来确保执行顺序,它是否已经足够好了?如果没有,如何进行控制?

    2 回复  |  直到 7 年前
        1
  •  0
  •   Anvesh Vejandla    7 年前

    对于Java8+,我建议使用Completable Futures。它完全支持您试图实现的用例。

    完全期货: Java 8

    示例算法如下所示:

    var cf=CompletableFuture.supplySync(()->processQuestion()).runAsync(()->过程响应)

    注:

    此外,关于完全期货的例子也很多

        2
  •  1
  •   Evgeniy Dorofeev    7 年前

     List<Future> futures = executorService.invokeAll(Arrays.asList(()->dssmCompute(), ()->dssmCompute()));