目前我有两个SwingWorker线程在后台工作.如果发生异常,该方法将停止工作,但该线程仍然运行.
如果发生异常,我如何停止执行并杀死doInBackground()的线程?
this.cancel(true)不要销毁/关闭线程.我怎样才能做到这一点?
@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的调试中看到了这些线程.
'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()已返回,仍然可以看到执行方法的线程,这是完全正常的.
您可以通过查看NetBeans报告的线程名称来识别此事实:SwingWorker-pool-1-thread-1,其中该池由SwingWorker管理.
如果需要更多控制,还可以将SwingWorker实例传递给Executor.
只需查看SwingWorker和Executor javadoc以获取更多信息.
此外,SwingWorker.cancel()不应该从doInBackground()调用,而是从另一个线程调用,通常是EDT,例如:当用户单击进度对话框中的“取消”按钮时.