📜  Java并发-期货和可赎回债券

📅  最后修改于: 2020-11-15 03:59:31             🧑  作者: Mango


与只能运行该线程的可运行接口相反,java.util.concurrent.Callable对象可以返回由线程完成的计算结果。 Callable对象返回Future对象,该对象提供方法来监视线程正在执行的任务的进度。 Future对象可用于检查Callable的状态,然后在线程完成后从Callable检索结果。它还提供了超时功能。

句法

//submit the callable using ThreadExecutor
//and get the result as a Future object
Future result10 = executor.submit(new FactorialService(10));
 
//get the result using get method of the Future object
//get method waits till the thread execution and then return the result of the execution.
Long factorial10 = result10.get();

下面的TestThread程序显示了在基于线程的环境中Future和Callables的用法。

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException,
      ExecutionException {

      ExecutorService executor = Executors.newSingleThreadExecutor();

      System.out.println("Factorial Service called for 10!");
      Future result10 = executor.submit(new FactorialService(10));

      System.out.println("Factorial Service called for 20!");
      Future result20 = executor.submit(new FactorialService(20));

      Long factorial10 = result10.get();
      System.out.println("10! = " + factorial10);

      Long factorial20 = result20.get();
      System.out.println("20! = " + factorial20);

      executor.shutdown();
   }  

   static class FactorialService implements Callable {
      private int number;

      public FactorialService(int number) {
         this.number = number;
      }

      @Override
      public Long call() throws Exception {
         return factorial();
      }

      private Long factorial() throws InterruptedException {
         long result = 1; 
         
         while (number != 0) { 
            result = number * result; 
            number--; 
            Thread.sleep(100); 
         }
         return result;    
      }
   }
}

这将产生以下结果。

输出

Factorial Service called for 10!
Factorial Service called for 20!
10! = 3628800
20! = 2432902008176640000