java.util.concurrent.Executor

1. java.util.concurrent.Executor
An object that executes submitted tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads. For example, rather than invoking new Thread(new(RunnableTask())).start() for each of a set of tasks, you might use:

Executor executor = anExecutor;
executor.execute(new RunnableTask1());
executor.execute(new RunnableTask2());

执行已提交的 Runnable 任务的对象。此接口提供一种将任务提交与每个任务将如何运行的机制(包括线程使用的细节、调度等)分离开来的方法。通常使用 Executor 而不是显式地创建线程。例如,可能会使用以下方法,而不是为一组任务中的每个任务调用 new Thread(new(RunnableTask())).start():

However, the Executor interface does not strictly require that execution be asynchronous. In the simplest case, an executor can run the submitted task immediately in the caller’s thread:

class DirectExecutor implements Executor {
      public void execute(Runnable r) {
          r.run();
      }
}

然而, Executor 接口并不强制要求任务的执行是异步的,可以在调用者的线程中同步执行。

More typically, tasks are executed in some thread other than the caller’s thread. The executor below spawns a new thread for each task.

class ThreadPerTaskExecutor implements Executor {
     public void execute(Runnable r) {
         new Thread(r).start();
     }
}

更多的情况是,任务在不同于调用者的线程中执行。

Many Executor implementations impose some sort of limitation on how and when tasks are scheduled. The executor below serializes the submission of tasks to a second executor, illustrating a composite executor.

更多的 Executor 实现会在任务的执行过程中强加一些限制,下面的 Executor 将任务传递到另一个 Executor 执行。

class SerialExecutor implements Executor {
    final Queue<Runnable> tasks = new Arra
    final Executor executor;
    Runnable active;
    SerialExecutor(Executor executor) {
        this.executor = executor;
    }
    public synchronized void execute(final Runna
        tasks.offer(new Runnable() {
            public void run() {
                try {
                    r.run();
                } finally {

                    scheduleNext();
                }
            }
        });
        if (active == null) {
            scheduleNext();
        }
    }
    protected synchronized void scheduleNext() {
        if ((active = tasks.poll()) != null) {
            executor.execute(active);
        }
    }
}

The Executor implementations provided in this package ExecutorService , which is a more extensive interface. The ThreadPoolExecutor class provides an extensible thread pool implementation. The Executors class provides convenient factory methods for these Executors. Memory consistency effects: Actions in a thread prior to submitting a object to an happen-before its execution begins, perhaps in another thread.

ExecutorService 实现了 Executor,这是一个使用更广泛的接口。 ThreadPoolExecutor 类提供一个可扩展的线程池实现。 Executors 类为这些 Executor 提供了便捷的工厂方法。

你可能感兴趣的:(java并发)