Java Future范例

时间:2020-02-23 14:37:08  来源:igfitidea点击:

异步计算的结果被称为Future,更具体地说,它之所以有这个名字,是因为它(结果)将在 The Future的稍后时间点完成。Future对象是在创建异步任务时创建的。提供了许多方法来帮助检索结果(使用 获取方法(这是唯一的检索方式))、使用 取消方法取消以及检查任务是否成功完成或者取消的方法。

Future的主要优点是它使我们能够同时执行其他进程,同时等待嵌入到Future中的主任务完成。这意味着,当我们面对大量计算时,使用Future将是一个好主意。

方法

布尔值取消(布尔值可能中断刷新)

  • V get()

  • V get(long timeout, TimeUnit unit)

这与上面的get方法不同,因为在这个方法中,指定了一个等待条件的超时

  • boolean isCancelled()

  • boolean isDone()

未来使用get(timeout,unit)的基本实现

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; 

public class FutureDemo 
{
  public static void main(String[] args) {
  	ExecutorService executorService = Executors.newSingleThreadExecutor();

  	Future<String> future = executorService.submit(() -> {
          Thread.sleep(5000);
          return "Done";
      });

      try {
          while(!future.isDone()) {
              System.out.println("Task completion in progress...");
              Thread.sleep(500);
          }

          System.out.println("Task completed!");
          String result = future.get(3000, TimeUnit.MILLISECONDS); //that's the future result
          System.out.println(result);

          executorService.shutdown();
      } 
      catch (InterruptedException e) {

      } 
      catch (ExecutionException e) {

      } 
      catch (TimeoutException e) { //this will be thrown if the task has not been completed within the specified time
      	future.cancel(true); // if this task has not started when cancel is called, this task should never run
      	future.isDone(); //will return true  
      	future.isCancelled(); //will return true 
      }   
  }
}

输出

Task completion in progress...
Task completion in progress...
Task completion in progress...
Task completion in progress...
Task completion in progress...
Task completion in progress...
Task completion in progress...
Task completion in progress...
Task completion in progress...
Task completion in progress...
Task completed!
Done

故障

对ExecutorService调用submit()方法,返回一个Future。既然我们有了未来,我们可以调用上面的方法。但是,我们需要特别注意的是,当提交的任务处于“运行”状态时,它正在打印“任务完成正在进行中…”。

如果任务没有在指定的时间内完成(如注释所示),将抛出TimeoutException捕获。