Java Callable and Future

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/vivianXuejun/article/details/80039709

前言:

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 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 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.

前言详细的说明了Callable 出现的原因:①能够返回线程执行的结果;②能够在执行call()方法的时候抛出异常。 这两点也正是 Runnable 与 Callable 的区别。
而其二,在 Callable 能够返回结果的时候,Future 就用来封装这个结果,而我们可以通过 Future 的 get() 方法得到这个结果。

以下是一个简单的例子:

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

public class CallableTest implements Callable<String> {

    @Override
    public String call() throws Exception {
        Thread.sleep(1000);
        return Thread.currentThread().getName();
    }

    public static void main(String[] args) {
        //Get ExecutorService from Executors utility class, thread pool size is 10
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        //create a list to hold the Future object associate with callable
        List<Future<String>> list = new ArrayList<Future<String>>();
        //create CallableTest instance
        Callable<String> callable = new CallableTest();
        for (int i=0; i<10; i++) {
            //submit callable task to be executed by thread pool
            Future<String> future = executorService.submit(callable);
            //add Future to the list, we can get return value using Future
            list.add(future);
        }

        for (Future<String> future: 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() + "::" + future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        //shut down the executor service now
        executorService.shutdown();
    }
}

另附优秀博文:
http://www.importnew.com/25286.html

猜你喜欢

转载自blog.csdn.net/vivianXuejun/article/details/80039709