|
| 1 | +package multithread.completablefutureexamples; |
| 2 | + |
| 3 | +import java.util.concurrent.CompletableFuture; |
| 4 | +import java.util.concurrent.ExecutionException; |
| 5 | +import java.util.concurrent.Executors; |
| 6 | +import java.util.concurrent.Future; |
| 7 | + |
| 8 | +import static org.junit.Assert.assertEquals; |
| 9 | + |
| 10 | +public class CompletableFutureDemo { |
| 11 | + private static final int MILLISECONDS_TO_FINISH_A_TASK = 1000; |
| 12 | + |
| 13 | + |
| 14 | + public static void main(String... args) throws Exception { |
| 15 | + System.out.println("Program started."); |
| 16 | + runApp(); |
| 17 | + System.out.println("Program ended."); |
| 18 | + } |
| 19 | + |
| 20 | + private static void runApp() throws InterruptedException, ExecutionException { |
| 21 | + Future<String> completableFuture = calculateAsync(); |
| 22 | + String result = completableFuture.get(); |
| 23 | + assertEquals("Hello", result); |
| 24 | + } |
| 25 | + |
| 26 | + private static Future<String> calculateAsync() { |
| 27 | + CompletableFuture<String> completableFuture = new CompletableFuture<>(); |
| 28 | + |
| 29 | + Executors.newCachedThreadPool().submit(() -> { |
| 30 | + Thread.sleep(1000); |
| 31 | + System.out.println("Doing some work in the thread now.."); |
| 32 | + completableFuture.complete("Hello"); |
| 33 | + return null; |
| 34 | + }); |
| 35 | + |
| 36 | + return completableFuture; |
| 37 | + } |
| 38 | + |
| 39 | + static class Worker implements Runnable { |
| 40 | + private String workerName; |
| 41 | + |
| 42 | + public Worker(String workerName) { |
| 43 | + this.workerName = workerName; |
| 44 | + } |
| 45 | + |
| 46 | + @Override |
| 47 | + public void run() { |
| 48 | + System.out.println(Thread.currentThread().getName() + " starting worker: " + workerName); |
| 49 | + doWork(); |
| 50 | + System.out.println(Thread.currentThread().getName() + " ended for worker: " + workerName); |
| 51 | + } |
| 52 | + |
| 53 | + private void doWork() { |
| 54 | + try { |
| 55 | + Thread.sleep(MILLISECONDS_TO_FINISH_A_TASK); |
| 56 | + } catch (InterruptedException e) { |
| 57 | + throw new RuntimeException(e); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments