|
JavaTM 2 Platform Standard Ed. 6 |
|||||||||
| 上一個類別 下一個類別 | 框架 無框架 | |||||||||
| 摘要: 巢狀 | 欄位 | 建構子 | 方法 | 詳細資訊: 欄位 | 建構子 | 方法 | |||||||||
public interface Executor
執行已提交的 Runnable 任務的物件。此介面提供一種將任務提交與每個任務將如何運行的機制(包括執行緒使用的細節、排程等)分離開來的方法。通常使用 Executor 而不是顯式地創建執行緒。例如,可能會使用以下方法,而不是為一組任務中的每個任務調用 new Thread(new(RunnableTask())).start():
Executor executor = anExecutor; executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2()); ...不過,Executor 介面並沒有嚴格地要求執行是非同步的。在最簡單的情況下,執行程序可以在調用者的執行緒中立即運行已提交的任務:
class DirectExecutor implements Executor {
public void execute(Runnable r) {
r.run();
}
}
更常見的是,任務是在某個不是調用者執行緒的執行緒中執行的。以下執行程序將為每個任務產生一個新執行緒。
class ThreadPerTaskExecutor implements Executor {
public void execute(Runnable r) {
new Thread(r).start();
}
}
許多 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 類別為這些 Executor 提供了便捷的處理器方法。
記憶體一致性效果:執行緒中將 Runnable 物件提交到 Executor 之前的操作 happen-before 其執行開始(可能在另一個執行緒中)。
| 方法摘要 | |
|---|---|
void |
execute(Runnable command)
在未來某個時間執行給定的命令。 |
| 方法詳細資訊 |
|---|
void execute(Runnable command)
command - 可運行的任務
RejectedExecutionException - 如果不能接受執行此任務。
NullPointerException - 如果命令為 null
|
JavaTM 2 Platform Standard Ed. 6 |
|||||||||
| 上一個類別 下一個類別 | 框架 無框架 | |||||||||
| 摘要: 巢狀 | 欄位 | 建構子 | 方法 | 詳細資訊: 欄位 | 建構子 | 方法 | |||||||||
版權所有 2008 Sun Microsystems, Inc. 保留所有權利。請遵守GNU General Public License, version 2 only。