SwingWorker 未按预期工作
我试图找到 SwingWorkerexecute() 与 doInBackground() 之间的差异。所以我编写了这个简单的程序来测试差异。
public static void main(String[] args) {
// TODO code application logic here
for(int i=0;i<10;i++){
try {
new Worker().execute();
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static class Worker extends SwingWorker<Void,Void>{
@Override
protected Void doInBackground() throws Exception {
System.out.println("Hello");
return null;
}
}
当我运行这个程序时,出现以下异常:
Exception in thread "AWT-Windows" java.lang.IllegalStateException: Shutdown in progress
at java.lang.ApplicationShutdownHooks.add(ApplicationShutdownHooks.java:39)
at java.lang.Runtime.addShutdownHook(Runtime.java:192)
at sun.awt.windows.WToolkit.run(WToolkit.java:281)
at java.lang.Thread.run(Thread.java:619)
但是,当我尝试使用 doInBackground() 时,
new Worker().doInBackground();
程序可以工作并打印预期结果。那么我的错误是什么?我是否应该使用 doInBackground() 方法,因为我已经读到不应该使用它。
谢谢
I'm trying to find the differences between SwingWorker execute() vs doInBackground().So I have written this simple program to test the difference.
public static void main(String[] args) {
// TODO code application logic here
for(int i=0;i<10;i++){
try {
new Worker().execute();
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static class Worker extends SwingWorker<Void,Void>{
@Override
protected Void doInBackground() throws Exception {
System.out.println("Hello");
return null;
}
}
When I run this program I got the following exception:
Exception in thread "AWT-Windows" java.lang.IllegalStateException: Shutdown in progress
at java.lang.ApplicationShutdownHooks.add(ApplicationShutdownHooks.java:39)
at java.lang.Runtime.addShutdownHook(Runtime.java:192)
at sun.awt.windows.WToolkit.run(WToolkit.java:281)
at java.lang.Thread.run(Thread.java:619)
However when I tried to use the doInBackground()
new Worker().doInBackground();
the program works and prints the expected result. So what is my error? and should I use the doInBackground() method as I have read that it shouldn't be used.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在当前线程上调用execute() 方法。它安排 SwingWorker 在工作线程上执行并立即返回。在您的情况下,主线程在计划的工作线程有机会执行
doInBackground()
方法之前退出。您可以使用get()
方法等待 SwingWorker 完成。The execute() method is called on the current thread. It schedules SwingWorker for the execution on a worker thread and returns immediately. In your case, the main thread exits before scheduled worker thread has a chance to execute
doInBackground()
method. You can wait for the SwingWorker to complete using theget()
methods.