共同学习Java源代码-多线程与并发-Executor、ExecutorService接口

来源:互联网 发布:星际争霸1数据修改 编辑:程序博客网 时间:2024/06/02 08:12

这段时间我来写多线程和并发相关类库的源代码 数据结构那块暂告一段落 但以后还会继续写数据结构的源代码 只不过最近换换口味


public interface Executor {

    void execute(Runnable command);
}

这个接口就一个方法 就是接收Runnable参数 并执行的方法


public interface ExecutorService extends Executor

ExecutorService接口继承自Executor接口


    void shutdown();

这个是关闭线程池的方法


    List<Runnable> shutdownNow();

关闭所有池中线程的方法 并且返回正在等待执行的线程的列表。


    boolean isShutdown();

判断线程池是否关闭


    boolean isTerminated();

判断池内所有线程是否都执行完了 如果提前调用了shutdown或shutdownNow方法 这个方法肯定返回false


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

阻塞这个方法的执行 执行线程池子线程任务 直到调用了shutdown方法并且子线程执行完毕 或者timeout时间过了 或者当前线程被打断 具体的实现看看子类吧 我也不是很懂


    <T> Future<T> submit(Callable<T> task);

这个方法是future提交的方法 执行callable任务然后返回future对象 


<T> Future<T> submit(Runnable task, T result);

和上面类似 成功执行时返回第二个参数 


Future<?> submit(Runnable task);

传入Runnable接口实现类 返回Future类


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

传入一系列Callable任务 返回一系列Future


    <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;

和上面类似 这个方法有时间限制


阅读全文
0 0
原创粉丝点击