[Java并发编程实战] Future+callable+FutureTask 闭锁机制(含示例代码)

业精于勤,荒于嬉;行成于思,毁于随。—韩愈
它告诉我们,事业的成功在于奋发努力,勤勉进取,太贪玩,放松要求便会一事无成;做事情要想成功,需要反复思考、深思熟虑,而随手随意、随随便便行事,做事不经过大脑,必然招致失败。

FutureTask 也可以做闭锁,它是 Future 和 callable 的结合体。所以我们有必要来了解 FutureTask 这个类。

FutureTask 的继承关系类图

先看 FutureTask 类的继承:

public class FutureTask<V> implements RunnableFuture<V> 

它继承自 RunnableFuture,可以看出他是 Runnable 和 Future 的结合体。

public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}

我们熟悉的 Runnable 接口:

public interface Runnable {
    public abstract void run();
}

不常见的Future 接口,用来获取异步计算结果:

public interface Future<V> {

    /**
     * Attempts to cancel execution of this task.  This attempt will
     * fail if the task has already completed, has already been cancelled,
     * or could not be cancelled for some other reason. If successful,
     * and this task has not started when {@code cancel} is called,
     * this task should never run.  If the task has already started,
     * then the {@code mayInterruptIfRunning} parameter determines
     * whether the thread executing this task should be interrupted in
     * an attempt to stop the task.
     */
    boolean cancel(boolean mayInterruptIfRunning);

    /**
     * Returns {@code true} if this task was cancelled before it completed
     * normally.
     */
    boolean isCancelled();//如果任务被取消,返回true

    /**
     * Returns {@code true} if this task completed.
     */
    boolean isDone();//如果任务执行结束,无论是正常结束或是中途取消还是发生异常,都返回true。

    /**
     * Waits if necessary for the computation to complete, and then
     * retrieves its result.
     */
    V get() throws InterruptedException, ExecutionException; //获取异步执行的结果,如果没有结果可用,此方法会阻塞直到异步计算完成。

    /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result, if available.
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

到这里,FutureTask 整个继承关系已经很清楚了。为了更直观一点,我用 starUML 画出它的类继承关系图。

这里写图片描述

在类关系图中,我们可以看到 FutureTask 的构造函数,包含了之前没有见过的类型:Callable。我们直接看下它的两个构造函数实现,进一步了解看看:

    //构造函数1
    public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }
    //构造函数2
    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

这里已经非常清楚了,最终都是赋值给 FutureTask 的内部变量 callable。它是一个接口,包含一个有返回值的函数 call()。

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,Runnable的关系了。那么,说了这么多主要是想干嘛呢?

没错,主要就是为了线程执行完成后能够返回结果。我们知道,Runnable 接口执行完成后,是没法返回结果的。所以,我们如果想要能够返回执行的结果,必须使用 callable 接口。

应用场景

比如我们有个耗时的计算操作,现在创建一个子线程执行计算操作,主线程通过 FutureTask.get() 的方式获取计算结果,如果计算还没有完成,则会阻塞一直等到计算完成

下面我们直接编写代码来实现上面的应用场景。

使用 Callable + FutureTask 获取执行结果:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class FutureTaskTest{

    //创建一个Future对象,并把Callable的实现传给构造函数
    private static final FutureTask<Integer> future = new FutureTask<Integer>(new CallableTest());

    public static void main(String[] args) {
        //创建一个线程
        final Thread thread = new Thread(future);
        //启动线程
        thread.start();
        try {
            Thread.sleep(1000);
            System.out.println("Main thread is running");
            //获取计算结果,会阻塞知道计算完毕
            System.out.println("get the sub thread compute result : " + future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("main thread is end");
    }

    //实现Callable接口,耗时操作
    static class CallableTest implements Callable<Integer>{
        @Override
        public Integer call() throws Exception {
            int ret = 0;
            Thread.sleep(1000);
            System.out.println("sub thread is computing");
            for(int i = 0; i < 1000; i++) {
                ret += i;
            }
            System.out.println("sub thread is finish compute");
            return ret;
        }   
    }
}

运行结果:
这里写图片描述

另外一种方式,是使用 Callable + Future + ExecutorService 的方式。ExecutorService继承自Executor,它的目的是为我们管理Thread对象,从而简化并发编程,Executor使我们无需显示的去管理线程的生命周期。

在ExecutorService接口中声明了若干个submit方法的重载版本:

<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task); 

第一个submit方法里面的参数类型就是Callable。

示例如下:

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;

public class FutureTaskTest{
    public static void main(String[] args) {
        //返回一个线程池,通常都和这种线程宽架搭配
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        System.out.println("Main thread is running");
        //提交给线程,返回一个Future类,并执行
        Future<Integer> future = threadPool.submit(new CallableTest());
        try {
            Thread.sleep(1000);
            //获取计算结果,会阻塞知道计算完毕
            System.out.println("get the sub thread compute result : " + future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("main thread is end");
    }
    //实现Callable接口,耗时操作
    static class CallableTest implements Callable<Integer>{
        @Override
        public Integer call() throws Exception {
            int ret = 0;
            Thread.sleep(1000);
            System.out.println("sub thread is computing");
            for(int i = 0; i < 1000; i++) {
                ret += i;
            }
            System.out.println("sub thread is finish compute");
            return ret;
        }   
    }
}

执行结果
这里写图片描述

本文完结,希望看完对你有帮助,欢迎关注我~

本文原创首发于微信公众号 [ 林里少年 ],欢迎关注第一时间获取更新。

猜你喜欢

转载自blog.csdn.net/amd123456789/article/details/80522855