当前位置: 代码网 > it编程>编程语言>Java > Java并发Futures和Callables类实例详解

Java并发Futures和Callables类实例详解

2024年05月28日 Java 我要评论
java.util.concurrent.callable对象可以返回由线程完成的计算结果,而runnable接口只能运行线程。 callable对象返回future对象,该对象提供监视线程执行的任务

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

到此这篇关于java并发futures和callables类的文章就介绍到这了,更多相关java futures和callables类内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com