4

我试图找出 SwingWorker execute() 与 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() 方法,因为我已经读过它不应该使用。

谢谢

4

1 回答 1

8

在当前线程上调用 execute() 方法。它安排 SwingWorker 在工作线程上执行并立即返回。在您的情况下,主线程在调度的工作线程有机会执行doInBackground()方法之前退出。您可以等待 SwingWorker 使用这些get()方法完成。

于 2010-10-06T06:25:34.310 回答