android Runnable Callable FutureTask

Runnable Callable FutureTask

都属于线程池中要被运行的任务
不同点:
Runnable是无返回值的任务,可以在线程中使用
Callable是有返回值的任务 ,不可以在线程中使用
FutureTask是有返回值,而且更易于管理和控制的任务,不可以在线程中使用;

FutureTask实现了RunnableFuture接口,而RunnableFuture继承了Runnable接口和Future接口,
Runnable是不可控制的任务 ,而Future为任务提供了一套标准来管理任务,Future提供了三种功能
1、判断任务是否完成
2、中断任务
3、获取任务执行结果

public interface Runnable {  
   /**这个任务运行完之后没有返回值*/  
    public abstract void run();  
}

public interface Callable<V> {  
   /**这个任务运行完之后返回泛型 V*/  
    V call() throws Exception; 
   //任务的具体过程,一旦任务传给ExecutorService的submit方法,call()方法自动在一个线程上执行  
}  

public interface Future<V> {  
    /**取消这个任务执行,传递参数是true,表示停止正在执行的任务,否则,这行完这次任务*/  
    boolean cancel(boolean mayInterruptIfRunning);  
    /**任务是否被取消*/<span style="white-space:pre">  </span>  
    boolean isCancelled();  
    /**任务是否完成*/  
    boolean isDone();  
    /**获取任务的返回结果*/  
    V get() throws InterruptedException, ExecutionException;  
    /**获取任务的结果,还没有完成就等待*/  
    V get(long timeout, TimeUnit unit)  
        throws InterruptedException, ExecutionException, TimeoutException;  
}

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

FutureTask实现了Runnable接口
FutureTask的两种构造: 
一个传递进去了Callable,另一个传递进去了Runable
Runable类型还是Callable类型任务,都统一构造成FutureTask类型(只接受Callable类型参数),如果是Runable类型,FutureTask构造内部会将它转为会Callable类型的变量传入FutureTask的构造;

public class FutureTask<V> implements RunnableFuture<V> {
    /** Synchronization control for FutureTask */
    private final Sync sync;

    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        sync = new Sync(callable);
    }

    public FutureTask(Runnable runnable, V result) {
        sync = new Sync(Executors.callable(runnable, result));
    }
    ...
    public void run() {
        sync.innerRun();
    }

    protected boolean runAndReset() {
        return sync.innerRunAndReset();
    }

    private final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = -7828117401763700385L;

        /** State value representing that task is ready to run */
        private static final int READY     = 0;
        /** State value representing that task is running */
        private static final int RUNNING   = 1;
        /** State value representing that task ran */
        private static final int RAN       = 2;
        /** State value representing that task was cancelled */
        private static final int CANCELLED = 4;

        /** The underlying callable */
        private final Callable<V> callable;
        /** The result to return from get() */
        private V result;
        /** The exception to throw from get() */
        private Throwable exception;

        /**
         * The thread running task. When nulled after set/cancel, this
         * indicates that the results are accessible.  Must be
         * volatile, to ensure visibility upon completion.
         */
        private volatile Thread runner;

        Sync(Callable<V> callable) {
            this.callable = callable;
        }
        ...

        void innerRun() {
            if (!compareAndSetState(READY, RUNNING))
                return;

            runner = Thread.currentThread();
            if (getState() == RUNNING) { // recheck after setting thread
                V result;
                try {
                    result = callable.call();
                } catch (Throwable ex) {
                    setException(ex);
                    return;
                }
                set(result);
            } else {
                releaseShared(0); // cancel
            }
        }

        boolean innerRunAndReset() {
            if (!compareAndSetState(READY, RUNNING))
                return false;
            try {
                runner = Thread.currentThread();
                if (getState() == RUNNING)
                    callable.call(); // don't set result
                runner = null;
                return compareAndSetState(RUNNING, READY);
            } catch (Throwable ex) {
                setException(ex);
                return false;
            }
        }
    }
}

Executors.callable()(Executors.java)
public class Executors {
    ...
    public static <T> Callable<T> callable(Runnable task, T result) {
        if (task == null)
            throw new NullPointerException();
        return new RunnableAdapter<T>(task, result);
    }

    static final class RunnableAdapter<T> implements Callable<T> {
        final Runnable task;
        final T result;
        RunnableAdapter(Runnable task, T result) {
            this.task = task;
            this.result = result;
        }
        public T call() {
            task.run();
            return result;
        }
    }
    ...
}

Runnable和Callable和FutureTask的执行:

public interface Executor {
    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the <tt>Executor</tt> implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution.
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}

public interface ExecutorService extends Executor {
    void shutdown();
    List<Runnable> shutdownNow();
    boolean isShutdown();
    boolean isTerminated();

    boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException;

    //ExecutorService的三个submit方法,提交任务
    <T> Future<T> submit(Callable<T> task);
    <T> Future<T> submit(Runnable task, T result);
    Future<?> submit(Runnable task);

    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
        throws InterruptedException;

    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
            long timeout, TimeUnit unit)throws InterruptedException;

    <T> T invokeAny(Collection<? extends Callable<T>> tasks)
        throws InterruptedException, ExecutionException;

    <T> T invokeAny(Collection<? extends Callable<T>> tasks,
                    long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

public abstract class AbstractExecutorService implements ExecutorService {
    //submit中提交的任务最终都会被转化为Callable类型的任务; 
    protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        return new FutureTask<T>(runnable, value); // 创建FutureTask,其本身实现了RunnableFuture接口,而RunnableFuture继承了Runnable接口,runnable 通过Executors.callable(runnable, result))最终转化成Callable
    }

    protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
        return new FutureTask<T>(callable);
    }

    //ExecutorService的抽象实现类AbstractExecutorService对三个submit方法做了实现---它们都调用了Executor接口中的execute(Runnable command)方法, RunnableFuture 接口继承了Runnable接口
    public Future<?> submit(Runnable task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<Void> ftask = newTaskFor(task, null);
        execute(ftask); 
        return ftask;
    }

    public <T> Future<T> submit(Runnable task, T result) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task, result);
        execute(ftask);
        return ftask;
    }

    public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }

    private <T> T doInvokeAny(Collection<? extends Callable<T>> tasks,
                            boolean timed, long nanos)
        throws InterruptedException, ExecutionException, TimeoutException {
        ...
    }

    public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
        throws InterruptedException, ExecutionException {
        try {
            return doInvokeAny(tasks, false, 0);
        } catch (TimeoutException cannotHappen) {
            assert false;
            return null;
        }
    }

    public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
                           long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        return doInvokeAny(tasks, true, unit.toNanos(timeout));
    }

    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
        throws InterruptedException {
        ...
    }

    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
                                         long timeout, TimeUnit unit)
        throws InterruptedException {
        ...
    }

}

示例:

ExecutorService mExecutorService = Executors.newCachedThreadPool();  
mExecutorService.submit(new Callable<String>() {  
    @Override  
    public String call() throws Exception {  
        System.out.println("我直接实现了Callable接口");  
        return "111";  
    }  
});

FutureTask<String> m1 = new FutureTask<String>(  
        new Callable<String>() {  
    @Override  
    public String call() throws Exception {  
        System.out.println("FutureTask  Callable");  
        return null;  
    }  
});  
mExecutorService.submit(m1);  

FutureTask<String> m2 = new FutureTask<String>(  
    new Runnable() {  
    @Override  
    public void run() {  
       System.out.println("FutureTask  Runnable");  
    }  
}, null);  
mExecutorService.submit(m2); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值