callable线程池示例

Java Callable and Future are used a lot in multithreaded programming. In last few posts, we learned a lot about java threads but sometimes we wish that a thread could return some value that we can use. Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.

Java Callable和Future在多线程编程中被大量使用。 在最近的几篇文章中,我们学到了很多有关Java线程的知识,但有时我们希望线程可以返回一些我们可以使用的值。 Java 5在并发包中引入了java.util.concurrent.Callable接口,该接口类似于Runnable接口,但是它可以返回任何Object并能够引发Exception。

Java可调用 (Java Callable)

Java Callable interface use Generic to define the return type of Object. Executors class provide useful methods to execute Java Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object.

Java Callable接口使用Generic定义Object的返回类型。 Executors类提供有用的方法来在线程池中执行Java Callable。 由于可调用任务并行运行,因此我们必须等待返回的Object。

Java的未来 (Java Future)

Java Callable tasks return java.util.concurrent.Future object. Using Java Future object, we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.

Java可调用任务返回java.util.concurrent.Future对象。 使用Java Future对象,我们可以找出Callable任务的状态并获取返回的Object。 它提供了get()方法,可以等待Callable完成,然后返回结果。

Java Future provides cancel() method to cancel the associated Callable task. There is an overloaded version of get() method where we can specify the time to wait for the result, it’s useful to avoid current thread getting blocked for longer time. There are isDone() and isCancelled() methods to find out the current status of associated Callable task.

Java Future提供了cancel()方法来取消关联的Callable任务。 get()方法的重载版本可以在其中指定等待结果的时间,这对于避免当前线程长时间阻塞很有用。 有isDone()isCancelled()方法来查找关联的Callable任务的当前状态。

Here is a simple example of Java Callable task that returns the name of thread executing the task after one second. We are using Executor framework to execute 100 tasks in parallel and use Java Future to get the result of the submitted tasks.

这是一个Java Callable任务的简单示例,该示例返回一秒钟后执行该任务的线程的名称。 我们使用Executor框架并行执行100个任务,并使用Java Future获取提交的任务的结果。

package com.journaldev.threads;import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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 MyCallable implements Callable<String> {@Overridepublic String call() throws Exception {Thread.sleep(1000);//return the thread name executing this callable taskreturn Thread.currentThread().getName();}public static void main(String args[]){//Get ExecutorService from Executors utility class, thread pool size is 10ExecutorService executor = Executors.newFixedThreadPool(10);//create a list to hold the Future object associated with CallableList<Future<String>> list = new ArrayList<Future<String>>();//Create MyCallable instanceCallable<String> callable = new MyCallable();for(int i=0; i< 100; i++){//submit Callable tasks to be executed by thread poolFuture<String> future = executor.submit(callable);//add Future to the list, we can get return value using Futurelist.add(future);}for(Future<String> fut : list){try {//print the return value of Future, notice the output delay in console// because Future.get() waits for task to get completedSystem.out.println(new Date()+ "::"+fut.get());} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}}//shut down the executor service nowexecutor.shutdown();}}

Once we execute the above program, you will notice the delay in output because java Future get() method waits for the java callable task to complete. Also notice that there are only 10 threads executing these tasks.

一旦执行了上述程序,您将注意到输出的延迟,因为java Future get()方法等待java可调用任务完成。 另请注意,只有10个线程执行这些任务。

Here is snippet of the output of above program.

这是上面程序输出的代码片段。

Mon Dec 31 20:40:15 PST 2012::pool-1-thread-1
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-2
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-3
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-4
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-5
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-6
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-7
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-8
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-9
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-10
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-2
...

Tip: What if we want to override some of the methods of Java Future interface, for example overriding get() method to timeout after some default time rather than waiting indefinitely, in this case Java FutureTask class comes handy that is the base implementation of Future interface. Check out Java FutureTask Example to learn more about this class.

提示 :如果我们要覆盖Java Future接口的某些方法,例如,将get()方法重写为在某个默认时间后超时而不是无限期等待,该怎么办?在这种情况下, Java FutureTask类很方便,它是Future的基本实现接口。 查看Java FutureTask示例,以了解有关此类的更多信息。

翻译自: https://www.journaldev.com/1090/java-callable-future-example

callable线程池示例

callable线程池示例_Java Callable Future示例相关推荐

  1. Java多线程系列--“JUC线程池”06之 Callable和Future

    转载自  Java多线程系列--"JUC线程池"06之 Callable和Future Callable 和 Future 简介 Callable 和 Future 是比较有趣的一 ...

  2. java callable 线程池_JAVA 线程池之Callable返回结果

    本文介绍如何向线程池提交任务,并获得任务的执行结果.然后模拟 线程池中的线程在执行任务的过程中抛出异常时,该如何处理. 一,执行具体任务的线程类 要想 获得 线程的执行结果,需实现Callable接口 ...

  3. java JUC线程池:Executors.newSingleThreadExecutor代码示例

    package com.zxl.juc;import java.util.concurrent.ExecutorService; import java.util.concurrent.Executo ...

  4. java 线程池 分组_JAVA面试题解惑系列(十)——话说多线程

    线程或者说多线程,是我们处理多任务的强大工具.线程和进程是不同的,每个进程都是一个独立运行的程序,拥有自己的变量,且不同进程间的变量不能共享:而线程是运行在进程内部的,每个正在运行的进程至少有一个线程 ...

  5. 线程池框架_Java并发——Executor框架详解(Executor框架结构与框架成员)

    一.什么是Executor框架? 我们知道线程池就是线程的集合,线程池集中管理线程,以实现线程的重用,降低资源消耗,提高响应速度等.线程用于执行异步任务,单个的线程既是工作单元也是执行机制,从JDK1 ...

  6. java 线程池扩容_java线程池自动扩容

    线程池构造方法有几个重要参数: public ThreadPoolExecutor(int corePoolSize,//核心线程数 int maximumPoolSize,//最大线程数 long ...

  7. java线程池并发_Java并发教程–线程池

    java线程池并发 Java 1.5中提供的最通用的并发增强功能之一是引入了可自定义的线程池. 这些线程池使您可以对诸如线程数,线程重用,调度和线程构造之类的东西进行大量控制. 让我们回顾一下. 首先 ...

  8. java手动线程池使用_Java手动配置线程池过程详解

    线程池中,常见有涉及到的: ExecutorService executorService = Executors.newSingleThreadExecutor(); ExecutorService ...

  9. java 线程池 包_Java并发包下线程池类小结

    并发包下的线程池技术虽然常用,但是知识点较多易忘.所以,参考网络资源做了一个小结,便于复习. 1.Executor接口 用于执行已提交的Runnable任务. Paste_Image.png 2.Ex ...

最新文章

  1. Python 之 matplotlib (九)contours等高线
  2. python typing typescript_Python的价值,对比Java/Typescript
  3. 深度学习核心技术精讲100篇(七)-keras 实战系列之深度学习模型处理多标签(multi_label)
  4. Nginx 最全操作总结
  5. java floatmath_《Java1.doc
  6. 如何开发 Node.js Native Add-on?
  7. java 中以||作为split分隔符正确的写法
  8. int.class 与 Integer.class
  9. conv2d的输入_pytorch1.0中torch.nn.Conv2d用法详解
  10. Python能做的事情很多别的编程语言也能做,python将会是昙花一现吗?看看这位程序员怎么说~
  11. python 数据结构包_python 中numpy科学计算工具包——基础数据结构
  12. 如何使用Node.js构建完整的GraphQL服务器
  13. 7-168 币值转换 (20 分)
  14. 详解Nacos的高可用特性(转载)
  15. c语言斐波那契数列前20项每行5个数,求c++:源程序。前20项斐波那契数列 ,要求输出的时候每行输出五个...
  16. 表格闪退怎么解决_excel2010表格打开闪退怎么回事
  17. 专业学习与职业发展之我见
  18. 在Linux下使用金山词霸2003(转)
  19. 通过js进行在线PDF电子签名和小编辑
  20. 在PC上通过手机发送短消息

热门文章

  1. extjs简单分页grid的总结
  2. (转)windows身份验证登入数据库 iis 无法访问数据库
  3. ASP.NET中常用的优化性能的方法(转贴,Icyer收集整理)
  4. [转载] Python学习笔记——用装饰器decorator和Memoization记忆化提高效率,原理讲清楚了
  5. 如何实现一个Servlet中的多个功能
  6. 别人的Linux私房菜(19)认识与分析日志文件
  7. jQueryEasyUI应用 – datagrid之CRUD应用
  8. UML类图几种关系的总结,泛化 = 实现 组合 聚合 关联 依赖
  9. Android学习笔记之AndroidManifest.xml文件解析(摘自皮狼的博客)
  10. GridView 中 DataFormatString 的使用