线程池基础类_ExecutorService(JDK1.8)

来源:互联网 发布:linux mib库在哪 编辑:程序博客网 时间:2024/06/16 13:28

Executor接口

public interface Executor {    /**     * 在未来某个时刻执行给定的任务     */    void execute(Runnable command);}

ExecutorService接口

作用:
1. 执行任务Runnable(execute方法)
2. 提交任务Runnable、Callable(submit方法)
3. 一次提交多个任务(invoke方法)
4. 关闭提交任务接口(shutdown方法)
5. 关闭、停止状态监测(isShutdown、isTerminated、awaitTermination方法)

/** * ExecutorService提供了管理终止和产生Future实例(用于跟踪异步任务进度)的方法。 *  * Executor一旦终止,就没有正在执行的任务,也没有正在等待执行的任务,并且不能提交新的任务。  * 应该关闭一个未使用的ExecutorService以允许资源的回收。 */public interface ExecutorService extends Executor {    /**     * 调用shutdown方法之后Executor会拒绝新的任务(task),     * 但允许在停止之前执行先前提交的任务     */    void shutdown();    /**     * 拒绝新的任务,并尝试停止正在执行和正在等待的任务,返回正在等待的任务列表     * 停止正在执行通常是通过Thread.interrupt()方法,这种情况无法终止不响应中断状态的线程     */    List<Runnable> shutdownNow();    //是否已经被shut down    boolean isShutdown();    //当executor被shut down,并且所有任务都被执行完,则返回ture,否则返回false    boolean isTerminated();    /**     * 阻塞直到下面任何一种情况发生     * 1.超过timeout指定的时间     * 2.调用shutdown,并且所有任务被执行完     * 3.当前线程被中断     */    boolean awaitTermination(long timeout, TimeUnit unit)        throws InterruptedException;    //提交Callable任务,并返回表示执行结果的Future实例    <T> Future<T> submit(Callable<T> task);    //提交Runnable任务,并返回表示任务的Future实例,通过该实例可以了解当前任务的执行状态    <T> Future<T> submit(Runnable task, T result);    Future<?> submit(Runnable task);    /**     * 执行给定的task,当所有task完成(执行完成、抛出异常)时,返回List<Future>     * 返回的每一个Future.isDone方法都返回true      */    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)        throws InterruptedException;    /**     * 执行给定的task,当所有task完成(执行完成、抛出异常)或超时时,     * 返回List<Future>,返回的每一个Future.isDone方法都返回true     * 返回的时候,那些来不及完成的任务都会被取消     */    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,                                  long timeout, TimeUnit unit)        throws InterruptedException;    /**     * 执行给定的任务,当有一个任务成功执行完成(未抛出异常),则返回该任务的结果     * 如果所有任务都不能成功完成执行,则抛出ExecutionException异常     */    <T> T invokeAny(Collection<? extends Callable<T>> tasks)        throws InterruptedException, ExecutionException;    /**     * 执行给定的任务,当有一个任务成功执行完成(未抛出异常),则返回该任务的结果     * 如果超时还未有任务成功完成执行,则抛出TimeoutException异常     * 如果所有任务都不能成功完成执行,则抛出ExecutionException异常     */    <T> T invokeAny(Collection<? extends Callable<T>> tasks,                    long timeout, TimeUnit unit)        throws InterruptedException, ExecutionException, TimeoutException;}

AbstractExecutorService

AbstractExecutorService实现了ExecutorService接口作用的第2和第3点(提交任务)
submit()实现:创建FutureTask,并交给execute()方法执行
invokeAny()实现:使用CompletionService提交任务,并获取结果,如果超时还未获取到结果,则抛出ExecutionException异常

/** * 通过newTaskFor方法返回的RunnableFuture实例,实现了submit, invokeAny * 和 invokeAll 方法,newTaskFor方法返回的RunnableFuture实例默认是FutureTask, * 子类可以覆盖newTaskFor方法以返回其他类的实例 */public abstract class AbstractExecutorService implements ExecutorService {    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);    }    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;    }    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));    }    private <T> T doInvokeAny(Collection<? extends Callable<T>> tasks,                              boolean timed, long nanos)        throws InterruptedException, ExecutionException, TimeoutException {        if (tasks == null)            throw new NullPointerException();        int ntasks = tasks.size();        if (ntasks == 0)            throw new IllegalArgumentException();        ArrayList<Future<T>> futures = new ArrayList<Future<T>>(ntasks);        //使用ExecutorCompletionService保存运行结果        ExecutorCompletionService<T> ecs =            new ExecutorCompletionService<T>(this);        try {            // 记录最后抛出的异常,如果最后没有获取到结果,则抛出该异常            ExecutionException ee = null;            final long deadline = timed ? System.nanoTime() + nanos : 0L;            Iterator<? extends Callable<T>> it = tasks.iterator();            // Start one task for sure; the rest incrementally            futures.add(ecs.submit(it.next()));            --ntasks;            int active = 1;            for (;;) {                Future<T> f = ecs.poll();                if (f == null) {                    if (ntasks > 0) {                        --ntasks;                        futures.add(ecs.submit(it.next()));                        ++active;                    }                    else if (active == 0)                        break;                    else if (timed) {                        f = ecs.poll(nanos, TimeUnit.NANOSECONDS);                        if (f == null)                            throw new TimeoutException();                        nanos = deadline - System.nanoTime();                    }                    else                        f = ecs.take();                }                if (f != null) {                    --active;                    try {                        return f.get();                    } catch (ExecutionException eex) {                        ee = eex;                    } catch (RuntimeException rex) {                        ee = new ExecutionException(rex);                    }                }            }            if (ee == null)                ee = new ExecutionException();            throw ee;        } finally {            for (int i = 0, size = futures.size(); i < size; i++)                futures.get(i).cancel(true);        }    }    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)        throws InterruptedException {        if (tasks == null)            throw new NullPointerException();        ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());        boolean done = false;        try {            for (Callable<T> t : tasks) {                RunnableFuture<T> f = newTaskFor(t);                futures.add(f);                execute(f);            }            for (int i = 0, size = futures.size(); i < size; i++) {                Future<T> f = futures.get(i);                if (!f.isDone()) {                    try {                        f.get();                    } catch (CancellationException ignore) {                    } catch (ExecutionException ignore) {                    }                }            }            done = true;            return futures;        } finally {            if (!done)                for (int i = 0, size = futures.size(); i < size; i++)                    futures.get(i).cancel(true);        }    }    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,                                         long timeout, TimeUnit unit)        throws InterruptedException {        if (tasks == null)            throw new NullPointerException();        long nanos = unit.toNanos(timeout);        ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());        boolean done = false;        try {            for (Callable<T> t : tasks)                futures.add(newTaskFor(t));            final long deadline = System.nanoTime() + nanos;            final int size = futures.size();            // Interleave time checks and calls to execute in case            // executor doesn't have any/much parallelism.            for (int i = 0; i < size; i++) {                execute((Runnable)futures.get(i));                nanos = deadline - System.nanoTime();                if (nanos <= 0L)                    return futures;            }            for (int i = 0; i < size; i++) {                Future<T> f = futures.get(i);                if (!f.isDone()) {                    if (nanos <= 0L)                        return futures;                    try {                        f.get(nanos, TimeUnit.NANOSECONDS);                    } catch (CancellationException ignore) {                    } catch (ExecutionException ignore) {                    } catch (TimeoutException toe) {                        return futures;                    }                    nanos = deadline - System.nanoTime();                }            }            done = true;            return futures;        } finally {            if (!done)                for (int i = 0, size = futures.size(); i < size; i++)                    futures.get(i).cancel(true);        }    }}
0 0
原创粉丝点击