forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFutureCancelEx.java
More file actions
50 lines (33 loc) · 1.25 KB
/
FutureCancelEx.java
File metadata and controls
50 lines (33 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.zetcode;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureCancelEx {
public static void main(String[] args) throws InterruptedException, ExecutionException {
int delay = new Random().nextInt(6) + 1;
ExecutorService executorService = Executors.newSingleThreadExecutor();
long startTime = System.nanoTime();
Future<String> future = executorService.submit(() -> {
Thread.sleep(2000);
return "message from callable";
});
while (!future.isDone()) {
System.out.println("working on task ...");
Thread.sleep(400);
double elapsedTimeInSec = (System.nanoTime() - startTime) / 1000000000.0;
if (elapsedTimeInSec > delay) {
future.cancel(true);
}
}
if (!future.isCancelled()) {
System.out.println("task completed");
String result = future.get();
System.out.println(result);
} else {
System.out.println("task cancelled");
}
executorService.shutdown();
}
}