2017-12-28 4 views
1

그래서이 코드를 새 스레드에서 실행하고 싶습니다.CompletableFuture를 새 스레드에서 병렬로 실행하는 방법

더 잘 설명하겠습니다. 나는 병렬로 실행하고 싶은 두 가지 방법이 있습니다.

public String method1(){ 
    ExecutorService pool = Executors.newSingleThreadExecutor(); 

    return CompletableFuture.supplyAsync(() -> { 
      //... 
     }, pool); 
} 


public String method2(){ 
    ExecutorService pool = Executors.newSingleThreadExecutor(); 

    return CompletableFuture.supplyAsync(() -> { 
      //... 
     }, pool); 
} 

그래서 병렬로 실행 & 다른 방법이 두 메소드를 호출하고 싶습니다.

public void method3(){ 
// Run both methods 
method1(); 
method2(); 
// end 
} 
+1

"내가 생각한대로 아래가 작동하지 않는다"는 의미에 대해 자세히 설명 할 수 있습니까? "일하지 않는"무엇입니까? 오류가 있습니까? 무슨 일이 일어날 것으로 예상됩니까? –

+0

@ChetanJadhavCD 제발 편집하십시오 – user123451

답변

0

메서드 서명이 반환 값과 일치하지 않습니다. 당신이 CompletableFuture를 반환하는 두 가지 방법을 변경하면 당신은 method3에서 예상되는 동작을 정의 할 수 있습니다

CompletableFuture<String> method1Future = method1(); 
CompletableFuture<String> method2Future = method2(); 

// example of expected behavior 
method1Future.thenCombine(method2Future, (s1, s2) -> s1 + s2); 

을 예에서 둘 다 선물이 완료되면 method1method2에 의해 비동기 적으로 공급되는 문자열을 연결할 것입니다 위.

관련 문제