Executor Java Doc 全解
本文是Executor Java Doc的翻譯
概述
這個介面是用來執行外部提交的Runnable任務的。它解耦了任務提交和任務執行方式,以及執行緒建立和排程的細節。Executor一般用來替代顯示地建立執行緒
舉個例子,
以前你是這樣:
Thread(new(RunnableTask())).start()
現在你最好這樣
Executor executor = anExecutor;
executor.execute(new RunnableTask1());
executor.execute(new RunnableTask2());
...
複製程式碼
不過,Executor介面並沒有嚴格要求一定要非同步執行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:
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