|
| 1 | +package io.mincong.concurrency.completablefuture; |
| 2 | + |
| 3 | +import java.time.LocalTime; |
| 4 | +import java.util.concurrent.CompletableFuture; |
| 5 | +import java.util.concurrent.Executors; |
| 6 | +import java.util.concurrent.TimeUnit; |
| 7 | + |
| 8 | +/** |
| 9 | + * Demo for comment 5130660255 in my blog "Why Do We Need Completable Future?": |
| 10 | + * https://mincong.io/2020/06/26/completable-future/#comment-5130660255 |
| 11 | + */ |
| 12 | +public class BlockingThreadDemo { |
| 13 | + |
| 14 | + /** |
| 15 | + * Possible output of the program: |
| 16 | + * |
| 17 | + * <pre> |
| 18 | + * [20:40:38.195492][main] Started |
| 19 | + * [20:40:38.189831][Thread-0] Started |
| 20 | + * [20:40:38.310267][main] 0 |
| 21 | + * [20:40:38.312907][main] 1 |
| 22 | + * [20:40:38.313041][main] 2 |
| 23 | + * [20:40:38.313145][main] 3 |
| 24 | + * [20:40:38.313252][main] 4 |
| 25 | + * [20:40:38.313344][main] 5 |
| 26 | + * [20:40:38.313429][main] 6 |
| 27 | + * [20:40:38.313518][main] 7 |
| 28 | + * [20:40:38.313604][main] 8 |
| 29 | + * [20:40:38.313700][main] 9 |
| 30 | + * [20:40:38.313802][main] Finished |
| 31 | + * [20:40:40.178991][Thread-0] Hello! |
| 32 | + * [20:40:40.179161][Thread-0] Finished |
| 33 | + * </pre> |
| 34 | + * |
| 35 | + * The "main" thread finished around 20:40:38.3 while the "Thread-0" finished around 20:40:40.1. |
| 36 | + * The two seconds delay was caused by the scheduler, which schedule the completion of the future |
| 37 | + * 2 seconds in the future. From this demo, we can see that where the main thread was not blocked |
| 38 | + * by the completable future. Only the worker thread "Thread-0" was blocked. |
| 39 | + */ |
| 40 | + public static void main(String[] args) { |
| 41 | + var workerFuture = new CompletableFuture<String>(); |
| 42 | + |
| 43 | + var thread = |
| 44 | + new Thread( |
| 45 | + () -> { |
| 46 | + print("Started"); |
| 47 | + final String workerAnswer; |
| 48 | + try { |
| 49 | + workerAnswer = workerFuture.get(); |
| 50 | + } catch (Exception e) { |
| 51 | + e.printStackTrace(); |
| 52 | + return; |
| 53 | + } |
| 54 | + print(workerAnswer); |
| 55 | + print("Finished"); |
| 56 | + }); |
| 57 | + thread.start(); |
| 58 | + |
| 59 | + var executor = Executors.newSingleThreadScheduledExecutor(); |
| 60 | + try { |
| 61 | + executor.schedule(() -> workerFuture.complete("Hello!"), 2, TimeUnit.SECONDS); |
| 62 | + |
| 63 | + print("Started"); |
| 64 | + for (int i = 0; i < 10; i++) { |
| 65 | + print(i); |
| 66 | + } |
| 67 | + print("Finished"); |
| 68 | + } finally { |
| 69 | + executor.shutdown(); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + private static void print(Object message) { |
| 74 | + var thread = Thread.currentThread().getName(); |
| 75 | + System.out.println("[" + LocalTime.now() + "][" + thread + "] " + message); |
| 76 | + } |
| 77 | +} |
0 commit comments