线程池原理–执行器ExecutorService

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011676300/article/details/83048436


线程池原理–总索引

线程池原理–执行器ExecutorService

ExecutorService 也是一个接口,继承Executor接口。

java interface ExecutorService extends Executor

相关方法

shutdown

  • shutdown: 当线程池调用该方法时,线程池的状态则立刻变成SHUTDOWN状态,此时调用isShutdown()会返回true。此时,则不能再往线程池中添加任何任务,否则将会抛出RejectedExecutionException异常。但是,此时线程池不会立刻退出,直到添加到线程池中的任务都已经处理完成,才会退出。
  • shutdownNow : 执行该方法,线程池的状态立刻变成STOP状态,此时调用isShutdown()会返回true,并试图停止所有正在执行的线程,不再处理还在池队列中等待的任务,当然,它会返回那些未执行的任务。此时,则不能再往线程池中添加任何任务,否则将会抛出RejectedExecutionException异常。它试图终止线程的方法是通过调用Thread.interrupt()方法来实现的,但是大家知道,这种方法的作用有限,如果线程中没有sleep 、wait、Condition、定时锁等应用, interrupt()方法是无法中断当前的线程的。所以,ShutdownNow()并不代表线程池就一定立即就能退出,它可能必须要等待所有正在执行的任务都执行完成了才能退出。
void shutdown();
List<Runnable> shutdownNow();
boolean isShutdown();
boolean isTerminated();

awaitTermination()等待线程池中的任务执行完成,可以设置超时时间,直到遇到这三种情况才会退出,
第一种.超时时间到。
第二种.所有的任务执行完后。
第三种.当前线程遇到中断。

@return {@code true} if this executor terminated and
     *  {@code false} if the timeout elapsed before termination
boolean awaitTermination(long timeout, TimeUnit unit)

submit

用于提交线程任务,线程任务可以是Callable或者Runnable接口的实现类。Future接口提供方法来检测任务是否被执行完,等待任务执行完获得结果。也可以设置任务执行的超时时间,这个设置超时的方法就是实现Java程序执行超时的关键。

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

批量提交任务

这四个方法都是批量提交任务,并返回结果。都会阻塞,invokeAll直到所有任务执行完毕才会退出阻塞状态。invokeAny只要有一个任务执行完毕就会退出阻塞状态。不过也可以设置超时时间。
如果发生任何异常,所有的任务都会被取消。

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

猜你喜欢

转载自blog.csdn.net/u011676300/article/details/83048436
今日推荐