javaswingsynchronizationinvokelaterinvokeandwait

How does a Java thread synchronize with invokeLater()?


I have a non-GUI thread that starts a JFrame using

java.awt.EventQueue.invokeLater(new Runnable() {

    public void run() {
        cardReadPunchGUI = new IBM1622GUI();  // instantiate
        cardReadPunchGUI.setVisible(true);
    }
});

Part of IBM1622GUI's constructor instantiates a "model" for itself, which my non-GUI thread needs access to:

cardReadPunch = IBM1622GUI.getModel();

What is the correct way for my non-GUI thread to synchronize with the new GUI that's been "invoked later"? (Without synchronization, of course, IBM1622GUI.getModel() just tends to return null.)


Solution

  • Use

    javax.swing.SwingUtilities.invokeAndWait(Runnable doRun);
    

    instead.

    Causes doRun.run() to be executed synchronously on the AWT event dispatching thread. This call blocks until all pending AWT events have been processed and (then) doRun.run() returns.