java并发-Executor

Executor

Executor只有一个execute方法,可以执行Runnable接口。

ExecutorService

ExecutorService继承自Executor

void shutdown();
List<Runnable> shutdownNow(); #停止正在执行的线程,返回等待的线程
boolean isShutdown();
boolean isTerminated();	//所有的线程都结束
boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException; //shutdown请求之后,阻塞等待所有的线程结束
<T> Future<T> submit(Callable<T> task); //提交一个任务,获得一个Future
<T> Future<T> submit(Runnable task, T result);//成功之后,调用Future的get方法返回result
Future<?> submit(Runnable task); //成功返回null
<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;

AbstractExecutorService

AbstractExecutorService抽象类实现ExecutorService

	//RunnableFuture既是一个Runnable,又是一个Future
 protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        return new FutureTask<T>(runnable, value);
    }
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
        return new FutureTask<T>(callable);
    }

问题callable和Runnable的区别

Future和Runnable

Future代表一个任务执行结果

Future代表异步执行的结果
boolean cancel(boolean mayInterruptIfRunning); //取消这个任务
boolean isCancelled();
boolean isDone(); //任务结束了,返回true
V get() throws InterruptedException, ExecutionException; //等待计算结束,获取结果

RunnableFuture继承自futrue和Runnable,只有一个run方法
FutureTask继承自RunnableFuture类,全部实现了里面的内容
FutureTask具有开始和结束task的放啊

构造时,内部callable变量赋值,runnable也转化为callable,状态机为new

    private Callable<V> callable;
    /** The result to return or exception to throw from get() */
    private Object outcome; // non-volatile, protected by state reads/writes
    /** The thread running the callable; CASed during run() */
    private volatile Thread runner;
    /** Treiber stack of waiting threads */
    private volatile WaitNode waiters;

posted @ 2016-08-09 11:56  zhangshihai1232  阅读(109)  评论(0)    收藏  举报