简体   繁体   English

SwingWorker无法按预期工作

[英]SwingWorker doesn't work as expected

I'm trying to find the differences between SwingWorker execute() vs doInBackground().So I have written this simple program to test the difference. 我试图找到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;
    }

}

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() 但是,当我尝试使用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. 我应该使用doInBackground()方法,因为我已经读过它不应该使用它。

Thanks 谢谢

The execute() method is called on the current thread. 在当前线程上调用execute()方法。 It schedules SwingWorker for the execution on a worker thread and returns immediately. 它安排SwingWorker在工作线程上执行并立即返回。 In your case, the main thread exits before scheduled worker thread has a chance to execute doInBackground() method. 在您的情况下,主线程在计划的工作线程有机会执行doInBackground()方法之前退出。 You can wait for the SwingWorker to complete using the get() methods. 您可以等待SwingWorker使用get()方法完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM