本文介绍了如何取消SwingWorker的执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 目前我有两个SwingWorker线程在后台工作。如果发生异常,该方法将停止工作,但该线程仍然运行。 如果发生异常,我如何停止执行并终止 doInBackground()的线程? / p> this.cancel(true)不要破坏/关闭线程。我怎样才能实现这个目标? @Override protected Boolean doInBackground()抛出异常{ try { while(true){ //这里的一些代码返回true; } } catch(例外e){ this.cancel(true); //< - 这不取消线程返回false; } } 我在Netbeans的调试中看到了这些线程。 / p> 'AWT-EventQueue-0'emexecageção'AWT-Windows'emcuteção'SwingWorker- pool-1-thread-1'emexecúcn'WoingWorker-pool-1-thread-2'emexecureção // *emeperação=执行中 解决方案默认情况下, SwingWorker 重复使用工作线程,所以尽管 doInBackground()已经返回,仍然可以看到执行方法的线程,这是完全正常的。 您可以通过查看NetBeans报告的线程名来识别这一事实: SwingWorker-pool-1-thread-1 ,其中 pool 由 SwingWorker 管理。 如果你想要更多控制权,你也可以通过 SwingWorker 实例到执行者。 检查 SwingWorker 和 Executor javadoc获取更多信息。 此外,不应该从 doInBackground() >而是来自另一个线程,通常是EDT,例如当用户在进度对话框中单击取消按钮时。 Currently I have two SwingWorker threads doing job on background. If an exception occurs, the method stop to work, but the thread still runnig. How I do to stop the execution and kill the thread of the doInBackground() if an exception occurs?this.cancel(true) don't destroy/close the thread. How can I achieve this?@Overrideprotected 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; } }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 解决方案 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.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.If you want more control, you can also pass the SwingWorker instance to an Executor.Just check SwingWorker and Executor javadoc for further information.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的执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-09 22:14