我們有這樣的事情:
private SwingWorkerExecutor swingWorkerExecutor;
//...
protected void runChain(List<SwingWorker<Void>> chainWorkers,
final SwingWorkerExecutor.RunAfter<Void> runAfter,
final SwingWorkerExecutor.RunOnError runOnError)
{
final List<SwingWorker<Void>> remainingWorkers =
chainWorkers.subList(1, chainWorkers.size());
SwingWorkerExecutor.RunAfter<Void> chainRunAfter;
if (chainWorkers.size() > 1)
{
chainRunAfter = new SwingWorkerExecutor.RunAfter<Void>()
{
@Override
public void run(Void value)
{
runChain(remainingWorkers, runAfter, runOnError);
}
};
}
else
{
chainRunAfter = runAfter;
}
currentWorker = chainWorkers.get(0);
swingWorkerExecutor.execute(currentWorker, chainRunAfter, runOnError);
}
這是非常簡單的,海事組織,因爲在我們的例子中SwingWorkerExecutor實際上包含了所有的難以理解的東西:
public class DefaultSwingWorkerExecutor implements SwingWorkerExecutor
{
@Override
public <T> void execute(SwingWorker<T, ?> worker, RunAfter<T> after,
RunOnError onError)
{
worker.addPropertyChangeListener(
new RunAfterHandler<T>(worker, after, onError));
worker.execute();
}
private static class RunAfterHandler<T> implements PropertyChangeListener
{
private final SwingWorker<T, ?> worker;
private final RunAfter<T> after;
private final RunAfter<Throwable> onError;
protected RunAfterHandler(SwingWorker<T, ?> worker, RunAfter<T> after,
RunOnError onError)
{
this.worker = worker;
this.after = after;
this.onError = onError;
}
@Override
public void propertyChange(PropertyChangeEvent evt)
{
if ("state".equals(evt.getPropertyName()) &&
evt.getNewValue() == SwingWorker.StateValue.DONE)
{
if (worker.isCancelled())
{
return;
}
try
{
after.run(worker.get());
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
catch (ExecutionException e)
{
onError.run(e);
}
}
}
}
}
有一些缺少的接口whic h應該非常直截了當地在這裏看不到它們。
我們真正的部署SwingWorkerExecutor使用注入的ExecutorService而不是默認的執行(這減少了我們爲單個應用程序需要的線程池的數量)。但是我們引入SwingWorkerExecutor的真正原因是它簡化並標準化了處理SwingWorker的成功和錯誤條件,並且還允許替換單元測試的邏輯(我相信你知道,如果它們是單線程的,它會簡單得多。)正如你所看到的,你會在done()中的每一個SwingWorker中通常需要一堆樣板文件,所以我們將done()工作移到了回調中,而不是這樣做。
副作用就像在一個鏈中運行多個Swing工作者一樣,很容易實現。
聽起來像一個的BlockingQueue有可能會有所幫助(http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html)。 – 2009-05-27 14:56:08