public interface Executor
java.util.concurrent.Executor |
Known Indirect Subclasses |
执行提交的Runnable
任务的对象。 该接口提供了一种将任务提交与每个任务如何运行的机制解耦的方式,包括线程使用的细节,调度等。通常使用Executor
而不是显式创建线程。 例如,不是针对一组任务中的每一个调用new Thread(new RunnableTask()).start()
,您可以使用:
Executor executor = anExecutor();
executor.execute(new RunnableTask1());
executor.execute(new RunnableTask2());
...
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();
}
}
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.
class SerialExecutor implements Executor {
final Queue<Runnable> tasks = new ArrayDeque<>();
final Executor executor;
Runnable active;
SerialExecutor(Executor executor) {
this.executor = executor;
}
public synchronized void execute(final Runnable r) {
tasks.add(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 implement
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.
内存一致性效果:操作在一个线程提交之前 Runnable
对象到 Executor
happen-before其执行开始,也许在另一个线程。
Public methods |
|
---|---|
abstract void |
execute(Runnable command) 将来在某个时间执行给定的命令。 |
void execute (Runnable command)
将来在某个时间执行给定的命令。 该命令可以在新线程,池线程或调用线程中执行,具体由Executor
实现决定。
Parameters | |
---|---|
command |
Runnable : the runnable task |
Throws | |
---|---|
RejectedExecutionException |
if this task cannot be accepted for execution |
NullPointerException |
if command is null |