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
程序显示了基于线程的环境中futures
和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<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
到此这篇关于java并发futures和callables类的文章就介绍到这了,更多相关java futures和callables类内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论