停止/取消 SwingWorker 线程?
我试图找出如何在按下按钮时停止 SwingWorker 线程的运行。我一直在环顾四周,但在解决如何做到这一点时遇到了一些麻烦。目前,这就是我所拥有的:
new MySwingWorkerClass(args).execute();
然后我正在创建一个按钮,我想用它来停止线程:
button = new JButton("Stop");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Stop the swing worker thread
}
});
我已经环顾四周寻找答案,到目前为止我已经设法找到了取消方法。但我不明白如何用它来阻止我的摇摆工人。我尝试了以下方法,但没有成功:
SwingWorker.cancel(true);
I'm trying to find out how to stop a SwingWorker thread from running when I press a button. I have been looking around and I'm having some trouble working out how to do this. At the moment this is what I have:
new MySwingWorkerClass(args).execute();
I'm then creating a button which I want to use in order to stop the thread:
button = new JButton("Stop");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Stop the swing worker thread
}
});
I have already looked around in search of an answer, so far I have managed to find the cancel method. I don't understand how to use this to stop my swing worker though. I tried the following but it didn't work:
SwingWorker.cancel(true);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要保留对您的 SwingWorker 的引用,然后使用该引用来取消工作线程。
这是一个完整的示例:
You need to keep a reference to your SwingWorker, then you use that reference to cancel the worker thread.
Here is a full example:
您需要定期检查其已取消标志(即
isCancelled()
)。SwingWorker
离开如何处理中断由你决定。有关详细信息,请参阅取消后台任务。
You need to periodically check its cancelled flag (i.e.
isCancelled()
).SwingWorker
leaves how to handle the interrupt up to you.For more information, see Cancelling Background Tasks.
您可以尝试覆盖done()方法并将其放入try catch中并捕获java.util.concurrent.CancellationException。类似的东西
。
。
。
。
。
。
you can try overidding the done() method and put it in try catch and catch the java.util.concurrent.CancellationException. Something like
.
.
.
.
.
.
我认为每次停止后都必须重新启动计数器。
对于 startButton,您必须重新启动工作程序,如
使用
要停止您可以在 Worker 类中
私有布尔stopFlag = false;
添加
并在 Thread.sleep(60); 之后
最后将 stopFlag 的 setter 放在 Worker 类的末尾,顺便说
一下,如果你想要异常退出,你可以使用 cancel(true) 。
I think you have to restart the counter after every stop.
For startButton, you have to have worker restarted as in
To stop you can use
in Worker class
private boolean stopFlag = false;
and add
after Thread.sleep(60);
and finally put setter for stopFlag at the end of Worker class as
By the way, you can use cancel(true) if you want to have exception exit.