-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCallableDemo.java
48 lines (33 loc) · 916 Bytes
/
CallableDemo.java
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
package com.codecafe.concurrency.thread.basics.designathread;
import java.util.concurrent.*;
class MyMath {
public static int add(int a, int b) {
return a + b;
}
}
// Callable is useful where we want to return an object from the task
class MyAddTask implements Callable<Integer> {
int x;
int y;
public MyAddTask(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public Integer call() throws Exception {
int result = x + y;
return result;
}
}
public class CallableDemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
int x = 10;
int y = 20;
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(new MyAddTask(x, y));
while (!future.isDone()) ; // wait
int z = future.get();
executor.shutdown();
System.out.println("Result is " + z);
}
}