SwingWorkerを一スレッドずつ順番に実行する
Total: 3495
, Today: 3
, Yesterday: 2
Posted by aterai at
Last-modified:
概要
JTable
のセルに配置したJProgressBar
を操作するSwingWorker
タスクを一つずつ順番に実行します。
Screenshot
Advertisement
サンプルコード
ExecutorService executor = Executors.newSingleThreadExecutor();
// ...
protected final void addActionPerformed() {
int key = model.getRowCount();
SwingWorker<Integer, Integer> worker = new BackgroundTask() {
@Override protected void process(List<Integer> c) {
if (isCancelled()) {
return;
}
if (!isDisplayable()) {
System.out.println("process: DISPOSE_ON_CLOSE");
cancel(true);
executor.shutdown();
return;
}
c.forEach(v -> model.setValueAt(v, key, 2));
}
@Override protected void done() {
if (!isDisplayable()) {
System.out.println("done: DISPOSE_ON_CLOSE");
cancel(true);
executor.shutdown();
return;
}
String text;
int i = -1;
if (isCancelled()) {
text = "Cancelled";
} else {
try {
i = get();
text = i >= 0 ? "Done" : "Disposed";
} catch (InterruptedException | ExecutionException ex) {
text = ex.getMessage();
}
}
System.out.format("%s:%s(%dms)%n", key, text, i);
// executor.remove(this);
}
};
model.addProgressValue("example", 0, worker);
executor.execute(worker);
}
View in GitHub: Java, Kotlin解説
上記のサンプルでは、Executors.newSingleThreadExecutor()
で作成した単一スレッド用のexecutor
を使用して順番に一つづSwingWorker
を実行しています。
Executors.newSingleThreadExecutor()
で生成されるExecutorService
はExecutors.newFixedThreadPool(1)
のものとほぼ同じ
- デフォルトの
SwingWorker
は10
個のワーカ・スレッドを同時に実行可能- Swing - Maximum number of SwingWorker objects in a Swing app?
public abstract class SwingWorker<T, V> implements RunnableFuture<T> { /** * number of worker threads. */ private static final int MAX_WORKER_THREADS = 10; // ... executorService = new ThreadPoolExecutor(MAX_WORKER_THREADS, MAX_WORKER_THREADS, 10L, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(), threadFactory);
- Swing - Maximum number of SwingWorker objects in a Swing app?
参考リンク
- Executors#newSingleThreadExecutor() (Java Platform SE 8)
- JTableのセルにJProgressBarを表示
- [JDK-6880336] SwingWorker deadlocks due one thread in the swingworker-pool - Java Bug System