03 有返回结果的多线程

查看Runnable接口的抽象方法发现它的返回值是void,所以不使用线程间通信他是无法获取返回结果的,Java提供了另一个具有返回结果的接口Callable,我们分析一下源代码并写几个简单的例子。

Callable简介

java.util.concurrent.Callable也是一个接口,它实现了一个方法call(),他的参数和返回值都是一个泛型V,而且默认可以抛出异常。可以说是Runnable的进阶版本,适合用于需要返回结果的复杂计算和处理过程。

java.util.concurrent.Callable源码
public interface Callable {
    /**
     * 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,Runnable和FutureTask

java.util.concurrent.Future接口
Future是一个接口它定义了几个基本的方法:

java.util.concurrent.Future源代码(注释太长删掉了,需要可自行查看源代码):
public interface Future {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;

java.util.concurrent.RunnableFuture接口
它继承了Runnable和Future说明他的实现方法需要实现一个可执行方法体run()和Future中的抽象方法。

java.util.concurrent.RunnableFuture源代码:
public interface RunnableFuture extends Runnable, Future {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}

java.util.concurrent.FutureTask类
FutureTask是RunnableFuture接口的实现,首先分析他的两个构造方法,都需要需要传入一个,可选参数为返回值:

java.util.concurrent.FutureTask构造函数
/**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Callable}.
     *
     * @param  callable the callable task
     * @throws NullPointerException if the callable is null
     */
    public FutureTask(Callable callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

    /**
     * Creates a {@code FutureTask} that will, upon running, execute the
     * given {@code Runnable}, and arrange that {@code get} will return the
     * given result on successful completion.
     *
     * @param runnable the runnable task
     * @param result the result to return on successful completion. If
     * you don't need a particular result, consider using
     * constructions of the form:
     * {@code Future f = new FutureTask(runnable, null)}
     * @throws NullPointerException if the runnable is null
     */
    public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

isCancelled(),isDone(0和cannel()都是获取线程的状态和直接调用Thread.interrupt()中断线程,这里不做描述。看下核心的get()方法,如果未执行完成则等待系统完成否则直接返回结果,另一个重载方法只是多了一个超时参数不在分析:

java.util.concurrent.FutureTask.get()方法
 public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }

看下Run()方法,直接调用Callable.call()方法,并将执行结果赋值给result属性:

java.util.concurrent.FutureTask.run()方法
  public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

总结

FutureTask可以说是一个加强版的Runnable,他也是一个方法执行体,因为它实现了Runnable接口所以它可以作为Thread的初始化参数,Thread执行的时候会直接调用执行他的run()方法;而且它实现了Future接口,在run()中调用call()并将结果存储在属性中供get()方法获取,同时提供了一系列操作函数实现了线程执行状态的监控和线程终端也就是任务取消功能。

FutureTask的几种简单使用方式

实现了Callable接口的MyThreadCallable类:
import java.util.concurrent.Callable;
public class MyThreadCallable implements Callable {
    private String name;
    MyThreadCallable(String name){
        this.name=name;
    }
    @Override
    public String call(){
        try {
            Thread.sleep((int) Math.ceil(Math.random() * 100) * 100);
            System.out.println("MyThreadCallable "+name+" 执行了");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "MyThreadCallable "+name+" 返回值";
    }
}

测试方法代码

测试方法
 public static void testThreadCallable(){
        try { //需要捕获Callable执行的call()可能抛出的异常
            /**
             * 新建MyThreadCallable实现Callable接口
             */
            FutureTask futureTask=new FutureTask<>(new MyThreadCallable("A"));
            new Thread(futureTask).start();


            /**
             * 匿名内部类方式实现FutureTask
             */
            FutureTask futureTask2=new FutureTask(new Callable(){
                @Override
                public String call() throws Exception {
                    Thread.sleep((int) Math.ceil(Math.random() * 100) * 100);
                   System.out.println("匿名内部类线程 B 执行了");
                   return  "匿名内部类线程 B 返回值";
                }
            });
            new Thread(futureTask2).start();


            /**
             * 使用线程池
             * 强烈建议使用线程池不要自己显示创建线程
             */
            FutureTask futureTask3=new FutureTask<>(new MyThreadCallable("C"));
            FutureTask futureTask4=new FutureTask<>(new MyThreadCallable("D"));
            ExecutorService executor = Executors.newCachedThreadPool();
            executor.execute(futureTask3);
            executor.execute(futureTask4);

            //最后获取返回值,get()方法会阻塞当前进程
            Thread.sleep(1000);
            System.out.println(futureTask.get());
            System.out.println(futureTask2.get());
            System.out.println(futureTask3.get());
            System.out.println(futureTask4.get());


        }catch (Exception e){
            e.printStackTrace();
        }
    }

执行结果:

匿名内部类线程 B 执行了
MyThreadCallable D 执行了
MyThreadCallable C 执行了
MyThreadCallable A 执行了
MyThreadCallable A 返回值
匿名内部类线程 B 返回值
MyThreadCallable C 返回值
MyThreadCallable D 返回值

你可能感兴趣的:(03 有返回结果的多线程)