线程池系列--ExecutorService接口:关闭线程池

public interface     Executor {
        void execute(Runnable command); //1 无返回值;线程执行的task需要实现Runnable接口
}

public interface ExecutorService extends Executor {

    /**
     * Initiates an orderly shutdown in which previously submitted
     * tasks are executed, but no new tasks will be accepted.
     * Invocation has no additional effect if already shut down.
     */
    void shutdown(); // 2 关闭线程池资源。不再接受新的任务,之前提交的任务等待执行结束再关闭。

    /**
     * Attempts to stop all actively executing tasks, halts the
     * processing of waiting tasks, and returns a list of the tasks
     * that were awaiting execution.
     */
    List<Runnable> shutdownNow(); //3 立刻关闭

    /**
     * Returns {@code true} if this executor has been shut down.
     */
    boolean isShutdown();

    boolean isTerminated();

    /**
     * Blocks until all tasks have completed execution after a shutdown
     * request, or the timeout occurs, or the current thread is
     * interrupted, whichever happens first.
     */
     //4 等待一定时间,如果还有未完成的任务,返回false;都完成了,返回true
    boolean awaitTermination(long timeout, TimeUnit unit) 
        throws InterruptedException;
     //5 提交一个任务,异步非阻塞
    <T> Future<T> submit(Callable<T> task);
   
    <T> Future<T> submit(Runnable task, T result);

        Future<?> submit(Runnable task);
      //6 提交多个任务,阻塞等待任务完成
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
        throws InterruptedException;
        //7 提交多个任务,阻塞一定时间等待任务完成
    <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;
}

 线程池关闭流程:

jdk的api文档:

void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }


你可能感兴趣的:(线程池系列--ExecutorService接口:关闭线程池)