Creating threads through Callable and Future
i. create the implementation class of the Callable interface and implement the call method. The call method will be used as the thread execution body with return value and can throw an exception.
ii. Create an instance of the Callable implementation class and wrap the Callable object with the FutureTask class, which encapsulates the return value of the call method of the Callable object.
iii. use the FutureTask object as the target of the Thread object to create and start a new Thread.
iv. call the get method of the FutureTask object to get the return value after the execution of the sub thread.
1 public class TestCallable {
2 public static void main(String[] args) {
3 ThreadDemo td = new ThreadDemo();
4 //1.implement Callable Way, need FutureTask Implementation class to receive the result of the operation.
5 FutureTask<Integer> result = new FutureTask<>(td);
6 new Thread(result).start();
7 //2.Receive the result of thread operation
8 try {
9 Integer sum = result.get(); //FutureTask Can be used for blocking
10 System.out.println(sum);
11 System.out.println("------------------------------------");
12 } catch (InterruptedException | ExecutionException e) {
13 e.printStackTrace();
14 }
15 }
16 }
17 class ThreadDemo implements Callable<Integer>{
18 public Integer call() throws Exception {
19 int sum = 0;
20 for (int i = 0; i <= 100000; i++) {
21 sum += i;
22 }
23 return sum;
24 }
25 }
1 //Create a thread pool
2 ExecutorService pool = Executors.newFixedThreadPool(taskSize);
3 // Create multiple tasks with return values
4 List<Future> list = new ArrayList<Future>();
5 for (int i = 0; i < taskSize; i++) {
6 Callable c = new MyCallable(i + " ");
7 // Perform tasks and obtain Future object
8 Future f = pool.submit(c);
9 list.add(f);
10 }
11 // Close thread pool
12 pool.shutdown();
13 // Get the running results of all concurrent tasks
14 for (Future f : list) {
15 // from Future Object and output to the console
16 System.out.println("res: " + f.get().toString());
17 }