简体   繁体   中英

Java SwingWorker does not work in a main method?

I just try following code but the swingworker is not executing. If I put it in an action of a GUI application (in a button click event) it is executing. What is the technical reason for that?

public static void main(String[] args) {

    new SwingWorker<Object, Object>() {
        @Override
        protected Object doInBackground() throws Exception {
            System.out.println("do in background.....");
            return null;
        }
    }.execute();

}

See Concurrency in Swing: Initial Threads for more details.

It works after adding SwingUtilities.invokeAndWait

public static void main(String[] args) {

        try {
            SwingUtilities.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    new SwingWorker<Object, Object>() {
                        @Override
                        protected Object doInBackground() throws Exception {
                            System.out.println("do in background.....");
                            return null;
                        }
                    }.execute();

                }
            });
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

It is a timing issue. If the background task finishes before the main method it will print "do in background......":

public static void main(String[] args) throws Exception {

    new SwingWorker<Object, Object>() {
        @Override
        protected Object doInBackground() throws Exception {
            System.out.println("do in background.....");
            return null;
        }
    }.execute();

    Thread.sleep(100L);
}

If however main finishes before the background task had a chance to run, it will print nothing:

public static void main(String[] args) throws Exception {

    new SwingWorker<Object, Object>() {
        @Override
        protected Object doInBackground() throws Exception {
            Thread.sleep(100L);
            System.out.println("do in background.....");
            return null;
        }
    }.execute();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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