如何取消 SwingWorker 的执行? [英] How cancel the execution of a SwingWorker?

查看:29
本文介绍了如何取消 SwingWorker 的执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有两个 SwingWorker 线程在后台工作.如果发生异常,该方法将停止工作,但线程仍在运行.

Currently I have two SwingWorker threads doing job on background. If an exception occurs, the method stop to work, but the thread still runnig.

如果发生异常,如何停止执行并杀死doInBackground()的线程?

How I do to stop the execution and kill the thread of the doInBackground() if an exception occurs?

this.cancel(true) 不要破坏/关闭线程.我怎样才能做到这一点?

this.cancel(true) don't destroy/close the thread. How can I achieve this?

@Override
protected Boolean doInBackground() throws Exception {
        try {
            while (true) {
                //some code here                   
                return true;
            }
        } catch (Exception e) {       
            this.cancel(true); //<-- this not cancel the thread               
            return false;
        }
    }

我在 Netbeans 的调试中看到了这些线程.

I see these threads in the debug of Netbeans.

'AWT-EventQueue-0' em execução
'AWT-Windows' em execução
'SwingWorker-pool-1-thread-1' em execução
'SwingWorker-pool-1-thread-2' em execução

//*em execução = in execution

推荐答案

默认情况下,SwingWorker 重用工作线程,所以即使 doInBackground()code> 已返回,仍可查看执行您的方法的线程.

By default, SwingWorker reuses worker threads, so it is perfectly normal that, even though, doInBackground() has returned, to still see the thread that executed your method.

您可以通过查看线程名称来识别这一事实,正如 NetBeans 报告的那样:SwingWorker-pool-1-thread-1,其中 poolSwingWorker.

You can identify this fact by looking at the thread names, as reported by NetBeans: SwingWorker-pool-1-thread-1, where that pool is managed by SwingWorker.

如果你想要更多的控制,你也可以将 SwingWorker 实例传递给 Executor.

If you want more control, you can also pass the SwingWorker instance to an Executor.

只需检查 SwingWorkerExecutor javadoc 了解更多信息.

Just check SwingWorker and Executor javadoc for further information.

此外,SwingWorker.cancel() 不应该从 doInBackground() 调用,而是从另一个线程调用,通常是 EDT,例如当用户点击进度对话框中的取消按钮时.

Besides, SwingWorker.cancel() is not supposed to be called from doInBackground() but rather from another thread, generally the EDT, e.g. when user clicks a Cancel button in a progress dialog.

这篇关于如何取消 SwingWorker 的执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆