future封装了callable,thread封装future。
发布日期:2021-06-24 18:18:52 浏览次数:2 分类:技术文章

本文共 1105 字,大约阅读时间需要 3 分钟。

三、使用Callable,Future返回结果

总结:future封装了callable,thread封装future。将callable的返回结果封装在future中,thread封装future,这样thread执行完后,就可以从future中拿取线程执行结果。

总结:future封装了callable,thread封装future。将callable的返回结果封装在future中,thread封装future,这样thread执行完后,就可以从future中拿取线程执行结果。

总结:future封装了callable,thread封装future。将callable的返回结果封装在future中,thread封装future,这样thread执行完后,就可以从future中拿取线程执行结果。

 

Future<V>代表一个异步执行的操作,通过get()方法可以获得操作的结果,如果异步操作还没有完成,则,get()会使当前线程阻塞。FutureTask<V>实现了Future<V>和Runable<V>。Callable代表一个有返回值得操作。

Java代码  
  1. Callable<Integer> func = new Callable<Integer>(){  
  2.     public Integer call() throws Exception {  
  3.         System.out.println("inside callable");  
  4.         Thread.sleep(1000);  
  5.         return new Integer(8);  
  6.     }         
  7. };        
  8. FutureTask<Integer> futureTask  = new FutureTask<Integer>(func);  
  9. Thread newThread = new Thread(futureTask);  
  10. newThread.start();  
  11.   
  12. try {  
  13.     System.out.println("blocking here");  
  14.     Integer result = futureTask.get();  
  15.     System.out.println(result);  
  16. catch (InterruptedException ignored) {  
  17. catch (ExecutionException ignored) {  
  18. }  

 ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,返回Future。如果Executor后台线程池还没有完成Callable的计算,这调用返回Future对象的get()方法,会阻塞直到计算完成。

转载地址:https://blog.csdn.net/weixin_34248258/article/details/86364928 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:超酷的图像效果 (附demo; C#完成)
下一篇:redis、kafka、rabittMQ对比

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月19日 08时29分41秒