views:

42

answers:

1

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

+4  A: 

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 the get() methods.

Suresh Kumar
what about the exception?
Feras
The exception occurs because your program is already exiting when the workers are started.
Guillaume
How to solve it then?
Feras
When you add Thread.sleep(2000L); after the for-loop you'll get the expected result.
OliBlogger
Look at the API documentation http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html. You can use the get() method to wait.
Suresh Kumar