-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCallableFutureTest.java
More file actions
51 lines (36 loc) · 1.33 KB
/
Copy pathCallableFutureTest.java
File metadata and controls
51 lines (36 loc) · 1.33 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
51
package inverview.callable;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableFutureTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// FutureTask is a concrete class that implements both Runnable and Future
FutureTask<Integer>[] randomNumberTasks = new FutureTask[5];
for (int i = 0; i < 5; i++) {
Callable<Integer> callable = new CallableExample();
// Create the FutureTask with Callable
randomNumberTasks[i] = new FutureTask<Integer>(callable);
// As it implements Runnable, create Thread
// with FutureTask
Thread t = new Thread(randomNumberTasks[i]);
t.start();
}
for (int i = 0; i < 5; i++) {
// As it implements Future, we can call get()
System.out.println(randomNumberTasks[i].get());
// This method blocks till the result is obtained
// The get method can throw checked exceptions
// like when it is interrupted. This is the reason
// for adding the throws clause to main
}
}
}
class CallableExample implements Callable<Integer> {
public Integer call() throws Exception {
Random generator = new Random();
Integer randomNumber = generator.nextInt(10);
Thread.sleep(randomNumber * 1000);
return randomNumber;
}
}