Skip to content

Commit 05f2755

Browse files
authored
Create FutureEx.java
1 parent 840d19f commit 05f2755

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
}

0 commit comments

Comments
 (0)