Java Callable与Future线程详解

来源:互联网 发布:闪电分期淘宝合作商户 编辑:程序博客网 时间:2024/05/16 00:52

Callable,是Java1.5之后提供的一个接口,主要用于实现Java线程。通过Callable实现的线程可以获取线程指定的返回值,并且在线程方法执行时可以对异常进行处理。正是由于这两点使得Callable在使用场景上与Runnable不同。

Callable

Callable处于java.util.concurrent包下,该接口是一个泛型接口,泛型即指定的返回值的类型。在Callable接口下只定义了一个方法call(),该方法实现线程的具体方法并在方法完成返回结果(同时,有可能会抛出异常)。

package java.util.concurrent;public interface Callable<V> {    /**     * Computes a result, or throws an exception if unable to do so.     *     * @return computed result     * @throws Exception if unable to compute a result     */    V call() throws Exception;}

Future和FutureTask

在上面说过通过Callable实现的线程可以具有返回值,但是我们应该要怎么样获得线程的返回值呢?

这里我们需要使用Future接口,Future接口代表一个异步操作的结果。在Future接口中定义了一系列的方法,用于获取线程结果、判断线程是否执行完成等。

public interface Future<V> {    /*     *  试图取消此任务的执行。     *       *  如果任务已完成、或已取消,或者由于某些其他原因而无法取消,则该方法调用失败,即返回值为false。     *  当调用 cancel 时,如果调用成功,而此任务尚未启动,则此任务将永不运行。如果任务已经启动,     *  则 mayInterruptIfRunning 参数确定是否应该以试图停止任务的方式来中断执行此任务的线程。     *       *  此方法返回后,对 isDone() 的后续调用将始终返回 true。如果此方法返回 true,     *  则对 isCancelled() 的后续调用将始终返回 true。     */    boolean cancel(boolean mayInterruptIfRunning);    /*     *  如果在任务正常完成前将其取消,则返回 true     *     */    boolean isCancelled();    /*     *  如果任务已完成,则返回 true;否则,返回false     *     */    boolean isDone();    /*     *  获取任务的返回结果,该方法是一个阻塞方法,会一直等待线程结束才可以获取返回结果。     *     */    V get() throws InterruptedException, ExecutionException;    /*     *  在指定的时间内,获取任务的返回结果,否则会出现TimeoutException。     *     */    V get(long timeout, TimeUnit unit)        throws InterruptedException, ExecutionException, TimeoutException;}

FutureTask

FutureTask时Future的具体实现类,该类同时还实现了Runnable接口。
FutureTask一般常用于包装Callable或者Runnable对象,由于FutureTask实现了Runnable接口,FutureTask可以通过Executor执行。

关于FutureTask在下面会演示其具体用法,这里就不做详细介绍了。

Callable实例演示

实现Callable完成线程的执行,有两种方式:一是通过Thread;一是通过Executor。

import java.util.ArrayList;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;import java.util.concurrent.FutureTask;/** * * @author zhangke */public class Test {    /**     * @param args     * @throws ExecutionException     * @throws InterruptedException     */    public static void main(String[] args) throws InterruptedException, ExecutionException {        execByExecutors();        execByThread();    }    public static void execByThread() {        try {            // 1、创建一个callable对象            Callable callable = new Callable<Integer>() {                @Override                public Integer call() throws Exception {                    System.out.println("正在后台执行中...");                    Thread.sleep(3000);                    return (int) (Math.random() * 100);                }            };            // 2、通过FutureTask对callable对象进行封装            FutureTask<Integer> futureTask = new FutureTask<Integer>(callable);            // 3、启动线程执行后台任务            new Thread(futureTask).start();            // 4、判断任务是否完成没有完成则继续阻塞主线程            while (!futureTask.isDone()) {                Thread.sleep(1000);                System.out.println("执行中...");            }            // 5、当线程任务完成,通过get方法获取结果            System.out.println("执行完成,结果为:" + futureTask.get());        } catch (Exception e) {        }    }    public static void execByExecutors() {        try {            // 1、获取ExecutorService            ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();            // 2、创建一个集合,用于存储future            ArrayList<Future> futureList = new ArrayList<Future>();            //             for (int i = 0; i < 5; i++) {                // 3、 通过ExecutorService的submit提交执行Callable,将返回一个Future对象,通过集合保存线程结果                futureList.add(newSingleThreadExecutor.submit(new Callable<Integer>() {                    @Override                    public Integer call() throws Exception {                        System.out.println("正在后台执行中...");                        Thread.sleep(3000);                        return (int) (Math.random() * 100);                    }                }));            }            // 4、遍历线程的结果            for (Future future2 : futureList) {                System.out.println(future2.get());            }            System.out.println("执行完成");            // 5、关闭线程池            newSingleThreadExecutor.shutdown();        } catch (Exception e) {            e.printStackTrace();        }    }}

运行结果为:

// execByThread正在后台执行中...执行中...执行中...执行中...执行完成,结果为:80// execByExecutor正在后台执行中...16正在后台执行中...正在后台执行中...7552正在后台执行中...正在后台执行中...8140执行完成
0 0
原创粉丝点击