博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
callable线程池示例_Java Callable Future示例
阅读量:2531 次
发布时间:2019-05-11

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

callable线程池示例

Java Callable and Future are used a lot in multithreaded programming. In last few posts, we learned a lot about 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 5在并发包中引入了java.util.concurrent.Callable接口,该接口类似于Runnable接口,但是它可以返回任何Object并能够引发Exception。

Java可调用 (Java Callable)

Java Callable interface use Generic to define the return type of Object. 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的返回类型。 类提供有用的方法来在线程池中执行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 to execute 100 tasks in parallel and use Java Future to get the result of the submitted tasks.

这是一个Java Callable任务的简单示例,该示例返回一秒钟后执行该任务的线程的名称。 我们使用并行执行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
{ @Override public String call() throws Exception { Thread.sleep(1000); //return the thread name executing this callable task return Thread.currentThread().getName(); } public static void main(String args[]){ //Get ExecutorService from Executors utility class, thread pool size is 10 ExecutorService executor = Executors.newFixedThreadPool(10); //create a list to hold the Future object associated with Callable List
> list = new ArrayList
>(); //Create MyCallable instance Callable
callable = new MyCallable(); for(int i=0; i< 100; i++){ //submit Callable tasks to be executed by thread pool Future
future = executor.submit(callable); //add Future to the list, we can get return value using Future list.add(future); } for(Future
fut : list){ try { //print the return value of Future, notice the output delay in console // because Future.get() waits for task to get completed System.out.println(new Date()+ "::"+fut.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } //shut down the executor service now executor.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-1Mon Dec 31 20:40:16 PST 2012::pool-1-thread-2Mon Dec 31 20:40:16 PST 2012::pool-1-thread-3Mon Dec 31 20:40:16 PST 2012::pool-1-thread-4Mon Dec 31 20:40:16 PST 2012::pool-1-thread-5Mon Dec 31 20:40:16 PST 2012::pool-1-thread-6Mon Dec 31 20:40:16 PST 2012::pool-1-thread-7Mon Dec 31 20:40:16 PST 2012::pool-1-thread-8Mon Dec 31 20:40:16 PST 2012::pool-1-thread-9Mon Dec 31 20:40:16 PST 2012::pool-1-thread-10Mon 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 to learn more about this class.

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

翻译自:

callable线程池示例

转载地址:http://hllzd.baihongyu.com/

你可能感兴趣的文章
小D课堂 - 新版本微服务springcloud+Docker教程_3-04 SpringCloud微服务核心组件Eureka介绍和闭源后影响...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_3-05 服务注册和发现Eureka Server搭建实战...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_3-06 服务注册和发现之Eureka Client搭建商品服务实战...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_3-07 Eureka服务注册中心配置控制台问题处理...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_4-01 常用的服务间调用方式讲解
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_4-02 微服务调用方式之ribbon实战 订单调用商品服务...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_4-03 高级篇幅之Ribbon负载均衡源码分析实战...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_4-06 Feign核心源码解读和服务调用方式ribbon和Feign选择...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_4-05 微服务调用方式之feign 实战 订单调用商品服务...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_5-02 Netflix开源组件断路器
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_5-01分布式核心知识之熔断、降级
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_5-04 feign结合hystrix断路器开发实战下...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_5-03 feign结合hystrix断路器开发实战上...
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_6-01 微服务网关介绍和使用场景
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_5-05熔断降级服务异常报警通知
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_6-03 高级篇幅之zuul常用问题分析
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_5-08 断路器监控仪表参数
查看>>
小D课堂 - 新版本微服务springcloud+Docker教程_6-02 springcloud网关组件zuul
查看>>
小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_2-1.快速搭建SpringBoot项目,采用Eclipse...
查看>>
小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_1-4.在线教育后台数据库设计...
查看>>