यह है एक ही बात नहीं। दूसरे उदाहरण में जहां thenApply
का उपयोग नहीं किया जाता है, यह निश्चित है कि convertToB
पर कॉल विधि doSomethingAndReturnA
विधि के समान थ्रेड में निष्पादित किया गया है।
लेकिन, पहले उदाहरण में जब thenApply
विधि प्रयोग किया जाता है अन्य बातों के हो सकता है।
सबसे पहले, जो doSomethingAndReturnA
निष्पादित करता है पूरा हो गया है, thenApply
का आवेषण कॉलर थ्रेड में होगा। यदि CompletableFutures
Function
thenApply
के लिए पारित doSomethingAndReturnA
रूप में एक ही धागे में सक्रिय किया जाएगा नहीं पूरा हो चुका है।
उलझन में? खैर this article might be helpful (लिंक के लिए @SotiriosDelimanolis धन्यवाद)।
मैं एक छोटी उदाहरण से बताया है कि कैसे काम करता है thenApply
प्रदान की है।
public class CompletableTest {
public static void main(String... args) throws ExecutionException, InterruptedException {
final CompletableFuture<Integer> future = CompletableFuture
.supplyAsync(() -> doSomethingAndReturnA())
.thenApply(a -> convertToB(a));
future.get();
}
private static int convertToB(final String a) {
System.out.println("convertToB: " + Thread.currentThread().getName());
return Integer.parseInt(a);
}
private static String doSomethingAndReturnA() {
System.out.println("doSomethingAndReturnA: " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "1";
}
}
और उत्पादन होता है:
doSomethingAndReturnA: ForkJoinPool.commonPool-worker-1
convertToB: ForkJoinPool.commonPool-worker-1
तो, जब पहला ऑपरेशन (अर्थात CompletableFuture
अभी तक पूर्ण नहीं है) धीमी है दोनों कॉल को एक ही धागे में होते हैं। लेकिन अगर हम उत्पादन doSomethingAndReturnA
से Thread.sleep
-call दूर करने के लिए थे, वे इस तरह (हो सकता है):
doSomethingAndReturnA: ForkJoinPool.commonPool-worker-1
convertToB: main
ध्यान दें कि convertToB
कॉल main
सूत्र में है।
यह उत्तर और यह पोस्ट (http://www.deadcoderising.com/java8-writing-asynchronous-code-with -completablefuture /) CompletableFuture – Jesus
को समझने में मेरी सहायता करें यह अभी भी यह नहीं समझाता है कि कोई 'तब लागू' क्यों उपयोग करेगा? – Yamcha
पहले मामले में, '' 'ForkJoinPool.commonPool-worker-1'' 'बस वहां लटका है और' कुछ' और कुछ और रिटर्न ''' '' '' '' '' 'कुछ और इंतजार कर रहा है? – Siddhartha