0

我有一个 Swingworker,有时我需要取消它。如果我执行然后取消,它会按预期工作。如果我运行该 Swingworker 的新实例,然后尝试取消它,则调用取消函数,它返回 true,但“doInBackground”方法完全运行而不会被取消。完全,我的意思是 Swingworker 线程运行的函数中的 while 循环完成(我只能在第一次取消)。

让我知道我是否清楚地说明了我的问题,这是一种我无法弄清楚的奇怪行为。

这是我的代码:

protected void firePlayButtonPlotWorker() {
    /*Cancel any previous plotWorker threads that may be running. The user might click the play
     * button again, so we ignore that if the thread isn't finished.*/
    if(plotWorker != null && !plotWorker.isDone())
    {
        System.err.println("Cancelling plot thread");
        plotWorker.cancel(true);
    }


    /*Create a SwingWorker so that the computation is not done on the Event Dispatch Thread*/
    plotWorker = new SwingWorker<Void, Void>() 
    {
        @Override
        public Void doInBackground() 
        {

            System.err.println("Plot Swing Worker Thread starting");
            playAudio(sceneManager.getScenes()); //Computation that requires an asynchronous while loop
            System.err.println("Plot Swing Worker Thread ended");
            return null;
        }

        @Override
        public void done() 
        {
            plotWorker = null;
        }
    };


    plotWorker.execute();
}

public void handleAudioEvent(AudioState audioState)
{
    switch (audioState)
    {
    case PLAY:
        firePlayButtonPlotWorker();
        break;
    case PAUSE:
        if(plotWorker != null)
        {
            boolean cancelBool = plotWorker.cancel(true);
            System.out.println("Cancelled? " + cancelBool);
        }
        break;
    case STOP:
        if(plotWorker != null)
        {
            plotWorker.cancel(true);
        }
        audioPlayerMarkerBean.setMarkerLocation(0);
        double[] coord = {0.0, 0.0};
        marker.drawMarker(coord);
        break;
    }
}
4

1 回答 1

2

使用 true 作为参数调用取消将使用Thread.interrupt方法中断线程。

因此,如果您的线程正在等待、休眠或加入,则会抛出 InterruptedException。否则,将设置线程的中断状态。

如果吞下 InterruptedException,线程将继续运行直到结束。如果线程在中断时正在运行(即没有等待、休眠或加入),它也会继续运行。您必须定期检查Thread.currentThread.isInterrupted()后台任务中线程(使用)的中断状态,并在它返回 true 时立即停止执行。

于 2011-02-25T22:45:00.037 回答