ScheduledThreadPoolExecutor(实现ScheduledExecutorService)似乎只在使用ScheduleAtFixedRate方法时运行一次SwingWorker类。原始代码有点长,所以我创建了一个新代码,在下面生成相同的结果。
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class ScheduledThreadPoolExecutorTest extends SwingWorker<Void, Void>{
@Override
protected Void doInBackground() {
System.out.println("Yay!");
return null;
}
@Override
protected void done() {
try {
get();
} catch(Exception e) {
e.printStackTrace();
}
System.out.println("Woohoo!");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(new ScheduledThreadPoolExecutorTest(), 0, 30, TimeUnit.MILLISECONDS);
}
});
}
}
这会产生结果:
Yay!
Woohoo!
为什么ScheduledThreadPoolExecutor只运行一次SwingWorker?我可以做些什么来使SwingWorker每30毫秒运行一次,如代码所示?
答案 0 :(得分:3)
虽然SwingWorker根据Runnable
方法的API部分确实实现了doInBackground()
界面:
请注意,此方法仅执行一次。
因此,虽然其内部run()
方法可能会重复运行,但doInBackground()
只会运行一次。不仅如此,run()
方法在SwingWorker中标记为final
,因此您无法覆盖它以多次调用doInBackground
。
更好的解决方案是根本不使用SwingWorker,而是使用更简单的Runnable派生类。
答案 1 :(得分:2)
SwingWorker扩展了Runnable,但它使用FutureTask来运行它的计算。
来自javadoc:
A cancellable asynchronous computation. This class provides a base
implementation of {@link Future}, with methods to start and cancel
a computation, query to see if the computation is complete, and
retrieve the result of the computation. The result can only be
retrieved when the computation has completed; the {@code get}
methods will block if the computation has not yet completed. Once
the computation has completed, the computation cannot be restarted
or cancelled (unless the computation is invoked using
{@link #runAndReset}).
也就是说,FutureTask只运行一次,如果你再试一次,它就会返回。
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}