本文是Executor Java Doc的翻譯bash
這個接口是用來執行外部提交的Runnable任務的。它解耦了任務提交和任務執行方式,以及線程建立和調度的細節。Executor通常用來替代顯示地建立線程app
舉個例子,異步
之前你是這樣: Thread(new(RunnableTask())).start()
this
如今你最好這樣spa
Executor executor = anExecutor;
executor.execute(new RunnableTask1());
executor.execute(new RunnableTask2());
...
複製代碼
不過,Executor接口並無嚴格要求必定要異步執行Runnable任務。 能夠參考下面的例子,你也能夠直接在調用者的線程中直接執行Runnable方法:線程
class DirectExecutor implements Executor {
public void execute(Runnable r) {
r.run();
}
}
複製代碼
可是一般狀況,最好仍是在另外一個線程去執行runnable:翻譯
class ThreadPerTaskExecutor implements Executor {
public void execute(Runnable r) {
new Thread(r).start();
}
}
複製代碼
許多Executor的實現都會加上一些功能限制,例如Runnable任務如何調度。 以下所示,下面的Executor將提交的任務傳遞給一個二級Executor:code
class SerialExecutor implements Executor {
final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
final Executor executor;
Runnable active;
SerialExecutor(Executor executor) {
this.executor = executor;
}
public synchronized void execute(final Runnable r) {
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);
}
}
}
複製代碼
Executor還有個子類ExecutorService,它提供更多的接口。ThreadPoolExecutor類提供了一個線程池實現。Executors類提供了不少方便的工廠方法。對象
Memory consistency effects: Actions in a thread prior to submitting a Runnable object to an Executor happen-before its execution begins, perhaps in another thread.接口
void execute(Runnable command)
在將來的某個時間點執行這個command對象。這個command任務可能會在一個新線程中執行,也可能會在一個池化的線程(某個線程池中的線程,可複用)中執行,甚至可能會在調用線程執行,具體是怎樣的取決於Executor的實現邏輯。
下面就不翻譯了,都能看懂
Parameters:
command - the runnable task
Throws: RejectedExecutionException - if this task cannot be accepted for execution NullPointerException - if command is null