我有一段JFrame
代码,SwingWorker
它在关闭时停止:
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;
/**
*
* @author yccheok
*/
public class JavaApplication11 extends JFrame {
public JavaApplication11() {
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
final Task task = new Task();
task.execute();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
if (task != null) {
task.cancel(true);
}
}
});
}
public class Task extends SwingWorker<Void, Void> {
@Override
protected Void doInBackground() {
for (int i = 0; i < 1000; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println("interrupted in doInBackground");
break;
}
System.out.println("-> " + i);
}
return null;
}
@Override
public void done() {
System.out.println("DONE!!!");
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new JavaApplication11().setVisible(true);
}
}
但是,随机地,我意识到当我关闭JFrame
,SwingWorker
的done
方法是在doInBackground
完成之前执行的。(你需要多次执行上面的JFrame才能产生问题)
-> 0
-> 1
-> 2
-> 3
-> 4
DONE!!!
interrupted in doInBackground
我可以知道为什么会这样吗?