File tree Expand file tree Collapse file tree
async/future-vs-completablefuture Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .zetcode ;
2+
3+ import java .util .concurrent .ExecutionException ;
4+ import java .util .concurrent .ExecutorService ;
5+ import java .util .concurrent .Executors ;
6+ import java .util .concurrent .Future ;
7+
8+ public class FutureEx {
9+
10+ public static void main (String [] args ) throws ExecutionException , InterruptedException {
11+
12+ ExecutorService executorService = Executors .newSingleThreadExecutor ();
13+
14+ Future <String > result = executorService .submit (() -> {
15+
16+ Thread .sleep (5000 );
17+
18+ return "success" ;
19+ });
20+
21+ for (int i =0 ; i <10 ; i ++) {
22+
23+ Thread .sleep (300 );
24+ System .out .println ("Doing task..." );
25+ }
26+
27+ // get is blocking
28+ // If the thread never finishes or takes too long to compute,
29+ // we can pass a timeout as an argument.
30+ // The isDone() method to check if the task has completed.
31+ var res = result .get ();
32+
33+ System .out .println (res );
34+
35+ executorService .shutdown ();
36+ }
37+ }
You can’t perform that action at this time.
0 commit comments