📜  ExecutorService接口

📅  最后修改于: 2020-11-15 03:56:34             🧑  作者: Mango


java.util.concurrent.ExecutorService接口是Executor接口的子接口,并添加了用于管理生命周期的功能,包括单个任务和执行程序本身。

ExecutorService方法

Sr.No. Method & Description
1

boolean awaitTermination(long timeout, TimeUnit unit)

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

2

List>invokeAll(Collection> tasks)

Executes the given tasks, returning a list of Futures holding their status and results when all complete.

3

List>invokeAll(Collection> tasks, long timeout, TimeUnit unit)

Executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires, whichever happens first.

4

T invokeAny(Collection> tasks)

Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do.

5

T invokeAny(Collection> tasks, long timeout, TimeUnit unit)

Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do before the given timeout elapses.

6

boolean isShutdown()

Returns true if this executor has been shut down.

7

boolean isTerminated()

Returns true if all tasks have completed following shut down.

8

void shutdown()

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

9

List shutdownNow()

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

10

Futuresubmit(Callable task)

Submits a value-returning task for execution and returns a Future representing the pending results of the task.

11

Future submit(Runnable task)

Submits a Runnable task for execution and returns a Future representing that task.

12

Futuresubmit(Runnable task, T result)

Submits a Runnable task for execution and returns a Future representing that task.

以下TestThread程序显示了在基于线程的环境中ExecutorService接口的用法。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TestThread {

   public static void main(final String[] arguments) throws InterruptedException {
      ExecutorService executor = Executors.newSingleThreadExecutor();

      try {
         executor.submit(new Task());
         System.out.println("Shutdown executor");
         executor.shutdown();
         executor.awaitTermination(5, TimeUnit.SECONDS);
      } catch (InterruptedException e) {
         System.err.println("tasks interrupted");
      } finally {

         if (!executor.isTerminated()) {
            System.err.println("cancel non-finished tasks");
         }
         executor.shutdownNow();
         System.out.println("shutdown finished");
      }
   }

   static class Task implements Runnable {
      
      public void run() {
         
         try {
            Long duration = (long) (Math.random() * 20);
            System.out.println("Running Task!");
            TimeUnit.SECONDS.sleep(duration);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
   }       
}

这将产生以下结果。

输出

Shutdown executor
Running Task!
shutdown finished
cancel non-finished tasks
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at java.lang.Thread.sleep(Thread.java:302)
    at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:328)
    at TestThread$Task.run(TestThread.java:39)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:662)