callable线程池示例_Java Callable Future示例

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, java Future, java callable example, java executorservice 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> {

    @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<Future<String>> list = new ArrayList<Future<String>>();
        //Create MyCallable instance
        Callable<String> callable = new MyCallable();
        for(int i=0; i< 100; i++){
            //submit Callable tasks to be executed by thread pool
            Future<String> future = executor.submit(callable);
            //add Future to the list, we can get return value using Future
            list.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 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-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线程池示例

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值