SwingWorker does not work as expected

I am trying to find the differences between SwingWorker execute () vs doInBackground (). So I wrote this simple program to check 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 doInBackground ()

 new Worker().doInBackground(); 

The program runs and prints the expected result. So what is my mistake? and should I use the doInBackground () method since I read that it should not be used.

thanks

+4
source share
1 answer

The execute () method is called on the current thread. He plans SwingWorker to run in the workflow and returns immediately. In your case, the main thread exits before the scheduled workflow, has the ability to execute the doInBackground() method. You can wait for SwingWorker to complete using the get() methods.

+8
source

All Articles