gpt4 book ai didi

java - 为什么我的 Swingworker 仅在第一次取消其线程?

转载 作者:行者123 更新时间:2023-12-02 08:22:58 27 4
gpt4 key购买 nike

我有一个 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;
}
}

最佳答案

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

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

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

关于java - 为什么我的 Swingworker 仅在第一次取消其线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5123190/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com