Java并发 专题
您的位置:java > Java并发专题 > Java并发Futures和Callables类
Java并发Futures和Callables类
作者:--    发布时间:2019-11-20

java.util.concurrent.callable对象可以返回由线程完成的计算结果,而runnable接口只能运行线程。 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程序显示了基于线程的环境中futurescallables的使用。

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<long> result10 = executor.submit(new factorialservice(10));

      system.out.println("factorial service called for 20!");
      future<long> 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<long>{
      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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册