-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMyCallable.java
More file actions
47 lines (42 loc) · 1.54 KB
/
Copy pathMyCallable.java
File metadata and controls
47 lines (42 loc) · 1.54 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
package inverview.callable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(1000);
// return the thread name executing this callable task
return Thread.currentThread().getName();
}
public static void main(String args[]) {
// Get ExecutorService from Executors utility class, thread pool size is 10
ExecutorService executor = Executors.newFixedThreadPool(10);
// create a list to hold the Future object associated with Callable
List<Future<String>> list = new ArrayList<Future<String>>();
// Create MyCallable instance
Callable<String> callable = new MyCallable();
for (int i = 0; i < 100; i++) {
// submit Callable tasks to be executed by thread pool
Future<String> future = executor.submit(callable);
// add Future to the list, we can get return value using Future
list.add(future);
}
for (Future<String> fut : list) {
try {
// print the return value of Future, notice the output delay in console
// because Future.get() waits for task to get completed
System.out.println(new Date() + "::" + fut.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
// shut down the executor service now
executor.shutdown();
}
}