繁体   English   中英

ScheduledThreadPoolExecutor仅运行一次Swingworker

[英]ScheduledThreadPoolExecutor only runs Swingworker once

使用ScheduleAtFixedRate方法时,ScheduledThreadPoolExecutor(实现ScheduledExecutorService)似乎仅运行一次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毫秒运行一次?

虽然SwingWorker确实实现了Runnable接口,但是按照doInBackground()方法的其API部分:

请注意,此方法仅执行一次。

因此,尽管其内部run()方法可以重复运行,但doInBackground()只会运行一次。 不仅如此, run()方法在SwingWorker中被标记为final ,因此您无法覆盖它来多次调用doInBackground

更好的解决方案是根本不使用SwingWorker,而是使用更简单的Runnable派生类。

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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM