Java并发编程中的Futures和Callables类详细实例解析

零 Java教程评论101字数 2051阅读6分50秒阅读模式

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

语法文章源自灵鲨社区-https://www.0s52.com/bcjc/javajc/15115.html

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

实例文章源自灵鲨社区-https://www.0s52.com/bcjc/javajc/15115.html

以下TestThread程序显示了基于线程的环境中Futures和Callables的使用。文章源自灵鲨社区-https://www.0s52.com/bcjc/javajc/15115.html

  1. import java.util.concurrent.Callable;
  2. import java.util.concurrent.ExecutionException;
  3. import java.util.concurrent.ExecutorService;
  4. import java.util.concurrent.Executors;
  5. import java.util.concurrent.Future;
  6. public class TestThread {
  7.      public static void main(final String[] arguments) throws InterruptedException, ExecutionException {
  8.          ExecutorService executor = Executors.newSingleThreadExecutor();
  9.          System.out.println("Factorial Service called for 10!");
  10.          Future<Long> result10 = executor.submit(new FactorialService(10));
  11.          System.out.println("Factorial Service called for 20!");
  12.          Future<Long> result20 = executor.submit(new FactorialService(20));
  13.          Long factorial10 = result10.get();
  14.          System.out.println("10! = " + factorial10);
  15.          Long factorial20 = result20.get();
  16.          System.out.println("20! = " + factorial20);
  17.          executor.shutdown();
  18.      }
  19.      static class FactorialService implements Callable<Long&gt;{
  20.          private int number;
  21.          public FactorialService(int number) {
  22.              this.number = number;
  23.          }
  24.          @Override
  25.          public Long call() throws Exception {
  26.              return factorial();
  27.          }
  28.          private Long factorial() throws InterruptedException{
  29.              long result = 1;
  30.              while (number != 0) {
  31.              result = number * result;
  32.              number--;
  33.              Thread.sleep(100);
  34.              }
  35.              return result;
  36.          }
  37.      }
  38. }

这将产生以下结果。文章源自灵鲨社区-https://www.0s52.com/bcjc/javajc/15115.html

Factorial Service called for 10!
Factorial Service called for 20!
10! = 3628800
20! = 2432902008176640000文章源自灵鲨社区-https://www.0s52.com/bcjc/javajc/15115.html

文章源自灵鲨社区-https://www.0s52.com/bcjc/javajc/15115.html文章源自灵鲨社区-https://www.0s52.com/bcjc/javajc/15115.html

零
  • 转载请务必保留本文链接:https://www.0s52.com/bcjc/javajc/15115.html
    本社区资源仅供用于学习和交流,请勿用于商业用途
    未经允许不得进行转载/复制/分享

发表评论