Created
February 20, 2022 22:03
-
-
Save rubykv/fa1b064a23d6d2292de106a5177df99d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.java.latest; | |
import java.util.concurrent.CompletableFuture; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.ThreadFactory; | |
public class Sample { | |
public static void main(String[] args) throws InterruptedException, ExecutionException { | |
ExecutorService executor = Executors.newScheduledThreadPool(2, new MyThreadFactory()); | |
CompletableFuture<Integer> cf = CompletableFuture.supplyAsync(() -> { | |
return 1; | |
}, executor); | |
CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(() -> { | |
return 2; | |
}, executor); | |
CompletableFuture<Integer> result = cf.thenCombine(cf1, (x,y) -> { | |
return add(x,y); | |
}); | |
System.out.println("Result " + result.get()); | |
// shutdown executor manually | |
executor.shutdown(); | |
} | |
public static int add(int x, int y) { | |
return x + y; | |
} | |
} | |
class MyThreadFactory implements ThreadFactory { | |
static int i = 1; | |
public Thread newThread(Runnable r) { | |
Thread t = new Thread(r, "" + i); | |
i++; | |
return t; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment