The sample callable and future interfaces use methods for the Java custom task class to periodically execute tasks

  • 2020-04-01 02:48:52
  • OfStack

Callable and Future interfaces

Callable is an interface similar to Runnable, and the classes that implement the Callable interface and the classes that implement Runnable are tasks that can be performed by other threads.

There are several differences between Callable and Runnable:
(1) the method specified by Callable is call(), while the method specified by Runnable is run().
(2) the Callable task can return a value after execution, while the Runnable task cannot return a value.
(3) the call() method can throw an exception, but the run() method cannot.
(4) run the Callable task to get a Future object, which represents the result of asynchronous calculation.

It provides a way to check that the computation is complete, to wait for the computation to complete, and to retrieve the result of the computation.
The Future object can be used to understand the execution of the task, cancel the execution of the task, and obtain the result of the task execution.



package com.yao;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableAndFuture {
 
 public static class MyCallableClass implements Callable {
  //Sign a
  private int flag = 0;
  public MyCallableClass(int flag) {
   this.flag = flag;
  }
  public String call() throws Exception {
   if (this.flag == 0) {
    //If the flag value is 0, it returns immediately
    return "flag = 0";
   }
   if (this.flag == 1) {
    //If the flag value is 1, do an infinite loop
    try {
     while (true) {
      System.out.println("looping......");
      Thread.sleep(2000);
     }
    } catch (InterruptedException e) {
     System.out.println("Interrupted");
    }
    return "false";
   } else {
    //If falg is not 0 or 1, an exception is thrown
    throw new Exception("Bad flag value!");
   }
  }
 }
 public static void main(String[] args) {
  //Define three tasks of type Callable
  MyCallableClass task1 = new MyCallableClass(0);
  MyCallableClass task2 = new MyCallableClass(1);
  MyCallableClass task3 = new MyCallableClass(2);
  //Create a service that performs the task
  ExecutorService es = Executors.newFixedThreadPool(3);
  try {
   //Commit and execute the task, which returns a Future object when it starts,
   //The Future object can be manipulated if you want the result of the task execution or an exception
   Future future1 = es.submit(task1);
   //If the get method is called, 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 task is an infinite loop
   Thread.sleep(5000);
   System.out.println("task2 cancel: " + future2.cancel(true));
   //Gets the output of the third task, because executing the third task causes an exception
   //So the following statement will cause the 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 service
  es.shutdownNow();
 }
}


Related articles: