java 多线程知识梳理3

Callable Runable和Future FutureTask的使用

1 先看看接口定义

public interface Runnable {
    public abstract void run();//定义为void,和thread一样,无法返回执行结果
}
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;//返回入参类型的执行结果
}
2 调用,针对这两种类型的接口通过ExecutorService执行。
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。
Future接口定义:
public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning);//取消任务,如果成功就返回true
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;//获取任务执行结果,如果没有就阻塞
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
FutureTask:
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V> {
    void run();
}
是Future的唯一实现类,实现了Future的功能,同时增加了线程执行完成后回调的功能。
  public FutureTask(Runnable runnable, V result) {
        sync = new Sync(Executors.callable(runnable, result));
    }

    public boolean isCancelled() {
        return sync.innerIsCancelled();
    }

    public boolean isDone() {
        return sync.innerIsDone();
    }

    public boolean cancel(boolean mayInterruptIfRunning) {
        return sync.innerCancel(mayInterruptIfRunning);
    }
    public V get() throws InterruptedException, ExecutionException {
        return sync.innerGet();
    }
    public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        return sync.innerGet(unit.toNanos(timeout));
    }

    protected void done() { }//当线程执行完成后,调用该方法。可以实现自己的FutureTask类,实现该方法
    protected void set(V v) {
        sync.innerSet(v);
    }
    protected void setException(Throwable t) {
        sync.innerSetException(t);

    public void run() {
        sync.innerRun();
    }

    protected boolean runAndReset() {
        return sync.innerRunAndReset();
    }
posted @ 2015-03-10 13:50  xiongjianjun  阅读(142)  评论(0编辑  收藏  举报