99package ru .lionsoft .javase .hello .thread ;
1010
1111import java .util .concurrent .Callable ;
12+ import java .util .concurrent .CompletableFuture ;
1213import java .util .concurrent .FutureTask ;
14+ import java .util .concurrent .TimeUnit ;
15+ import java .util .concurrent .TimeoutException ;
1316
1417/**
1518 * Пример работы с Callable интерфейсом и асинхронное выполнение функции
1821public class HelloFuture {
1922
2023 public static void main (String [] args ) throws Exception {
24+
25+ testFutureTask ();
26+ testCompletableFuture ();
27+ }
28+
29+ public static void testFutureTask () throws Exception {
2130 Callable <String > task = () -> {
2231 try {
2332 Thread .sleep (500 );
@@ -27,6 +36,36 @@ public static void main(String[] args) throws Exception {
2736 };
2837 FutureTask <String > future = new FutureTask <>(task );
2938 new Thread (future ).start ();
30- System .out .println (future .get ());
39+ String hello = null ;
40+ int counter = 0 ;
41+ do {
42+ try {
43+ hello = future .get (10 , TimeUnit .MILLISECONDS );
44+ } catch (TimeoutException ex ) {
45+ System .err .println ("Timeout! #" + ++counter );
46+ }
47+ } while (hello == null );
48+ System .out .println ("Result: " + hello );
49+
50+ }
51+
52+ public static void testCompletableFuture () throws Exception {
53+ // CompletableFuture уже содержащий результат
54+ CompletableFuture <String > completed ;
55+ completed = CompletableFuture .completedFuture ("Просто значение" );
56+
57+ // CompletableFuture, запускающий (run) новый поток с Runnable, поэтому он Void
58+ CompletableFuture <Void > voidCompletableFuture ;
59+ voidCompletableFuture = CompletableFuture .runAsync (() -> {
60+ System .out .println ("run " + Thread .currentThread ().getName ());
61+ });
62+
63+ // CompletableFuture, запускающий новый поток, результат которого возьмём у Supplier
64+ CompletableFuture <String > supplier ;
65+ supplier = CompletableFuture .supplyAsync (() -> {
66+ System .out .println ("supply " + Thread .currentThread ().getName ());
67+ return "Значение" ;
68+ });
69+ System .out .println (supplier .get ());
3170 }
3271}
0 commit comments