Java SwingWorker 在 main 方法中不起作用?

Java SwingWorker does not work in a main method?

我只是尝试执行以下代码,但 swingworker 没有执行。如果我把它放在一个 GUI 应用程序的动作中(在按钮单击事件中),它就会执行。技术原因是什么?

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();

}

有关详细信息,请参阅 Concurrency in Swing: Initial Threads

添加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();
        }
    }

这是一个时间问题。如果后台任务在 main 方法之前完成,它将打印 "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);
}

但是,如果 main 在后台任务有机会 运行 之前完成,它将不会打印任何内容:

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();

}