Callable and Future

 Author Avatar
lucky January 15, 2020
  • Read this article on other devices

Callable is very similar to Runnable. The main difference is that Callable can return running results and throw exceptions.
The implementation of the Callable method requires the support of the Future implementation class to receive the operation results. FutureTask is the implementation class of the Future interface.

 public class TestCallable { public static void main(String[] args) { ThreadDemo td = new ThreadDemo(); //1. The implementation of the Callable method requires the support of the FutureTask implementation class to receive the calculation results. //Put a Callable object in the parameter FutureTask<Integer> result = new FutureTask<>(td); new Thread(result).start(); //2. Receive the result after thread operation try { Integer sum = result.get();  // FutureTask can be used to block functions similar to CountDownLatch. It will not be executed after all threads have not completed execution System.out.println(sum); System.out.println("------------------------------------"); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } class ThreadDemo implements Callable<Integer> { @Override public Integer call() throws Exception { int sum = 0; for (int i = 0; i <= 100000; i++) { sum += i; } return sum; } }

From the above examples, we can see the difference between the Callable and Future interfaces

(1) The method specified by Callable is call(), while the method specified by Runnable is run()
(2) Callable tasks can return values after execution, while Runnable tasks cannot.
(3) The call() method can throw exceptions, while the run() method cannot.
(4) Run the Callable task to get a Future object. Future represents the result of asynchronous calculation.
It provides a method to check whether the calculation is completed, wait for the completion of the calculation, and retrieve the results of the calculation.
The Future object can be used to understand task execution, cancel task execution, and obtain the results of task execution.
Callable is an interface similar to Runnable. Classes that implement the Callable interface and classes that implement Runnable are tasks that can be executed by other threads.

https://www.cnblogs.com/wzdnwyyu/p/11162973.html

Comments closed