Welcome to the public number [sharedCode] committed to mainstream middleware source code analysis, personal website: www.shared-code.com/

The Callable and Future functions were added in later versions of Java to accommodate the many-union method. Callable is an interface similar to Runnable. Classes that implement Callable interfaces and classes that implement Runnable are tasks that can be executed by other threads.

The Callable interface is defined as follows;

public interface Callable<V> { **

      V   call(a)   throws Exception; **

} 
Copy the code

The difference between Callable and Runnable is as follows:

I Callable defines the call method and Runnable defines the run method.

II The call method of a Callable can have a return value, while the run method of a Runnable cannot.

III The call method of a Callable can throw an exception, while the run method of a Runnable cannot.

The Future is introduced

The Future represents the result of an asynchronous computation and provides a way to check that the computation is complete, wait for it to complete, and retrieve the result of the computation. The Future’s cancel method can cancel the execution of a task, taking a Boolean parameter true to interrupt the task immediately and false to allow the running task to complete. The Future’s get method waits for the calculation to complete and retrieves the result

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

/** * Callable is a Runnable interface. Classes that implement Callable and classes that implement Runnable are tasks that can be executed by other threads. * There are several differences between Callable and Runnable: * (1) Callable calls call() while Runnable calls run(). * (2) Callable tasks return values, while Runnable tasks do not. * (3) The call() method can throw an exception, but the run() method cannot. * (4) Run the Callable task to get a Future object, * Future represents the result of the asynchronous calculation. It provides a way to check that a calculation is complete, wait for it to complete, and retrieve the results of the calculation. * Through the Future object, you can know the execution of the task, cancel the execution of the task, and obtain the results of the task execution. * /

public class CallableAndFuture {

   public static class  MyCallable  implements Callable{

         private int flag = 0; 

         public MyCallable(int flag){

                 this.flag = flag;

         }

         public String call(a) throws Exception{

             if (this.flag == 0) {return "flag = 0";

           } 

           if (this.flag == 1) {try {

                   while (true) {

                           System.out.println("looping.");

                           Thread.sleep(2000); }}catch (InterruptedException e) {

                             System.out.println("Interrupted");

               }

               return "false";

           } else {   

                      throw new Exception("Bad flag value!"); }}}public static void main(String[] args) {

      // Define three Callable tasks

       MyCallable task1 = new MyCallable(0);

       MyCallable task2 = new MyCallable(1);

       MyCallable task3 = new MyCallable(2);

       

      // Create a service to perform the task

       ExecutorService es = Executors.newFixedThreadPool(3);

       try {

          // Submit and execute the task. The task starts with a Future object,

           // If you want the result or exception of the task execution, you can operate on this Future object

           Future future1 = es.submit(task1);

          // Get the result of the first task. If you call get, the current thread waits for the task to complete before proceeding

           System.out.println("task1: " + future1.get());

           

           Future future2 = es.submit(task2);

          // Wait 5 seconds before stopping the second task. Because the second one goes in an infinite loop

           Thread.sleep(5000);

           System.out.println("task2 cancel: " + future2.cancel(true));

           

          // Get the output of the third task, because executing the third task raises an exception

           // So the following statement will cause an exception to be thrown

           Future future3 = es.submit(task3);

           System.out.println("task3: " + future3.get());

       } catch (Exception e){

           System.out.println(e.toString());

       }

      // Stop the task execution servicees.shutdownNow(); }}Copy the code