0

I'm a little confused with multi threading in Java, I have a GUI which I created a thread for and another project which acts as a server and is used to receive data from other data sources which is on a separate thread. The server's thread calls a method in one of the views on the GUI thread and updates a status, however the GUI doesn't update. How can I setup this architecture correctly. Here's what I have:

public static void main(String[] args) 
{
    //Connections
    Runnable r2 = new Runnable() {
        @Override
        public void run() 
        {
            App.connectToServer();
        }
    };

    //Launch main window
    Runnable r1 = new Runnable() {
        @Override
        public void run() 
        {
            //Installs theme
            WebLookAndFeel.install();

            //Launches main window
            BootWindow myMainWindow = new BootWindow();
        }
    };

    Thread thr1 = new Thread(r1);
    Thread thr2 = new Thread(r2);
    thr1.start();
    thr2.start();
}

//Server connections
private static void connectToServer()
{
    System.out.println("Connecting to the eTrade Manager Server..");
    etmServer server = new etmServer();
    server.connectEtmServer();

}
kknaguib
  • 749
  • 4
  • 12
  • 33

1 Answers1

0

If you are using AWT/Swing, the GUI runs on a special thread called the Event Dispatch Thread (EDT) and all GUI updates must run on that thread. so you would need to do this instead:

 SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        //code goes here
    }
  });

Keep in mind that Swing is single-threaded and is not thread-safe.

dramzy
  • 1,379
  • 1
  • 11
  • 25
  • ok now how do I refresh the GUI after when the thread with the server updates a component? @dramzy – kknaguib Oct 08 '14 at 15:13
  • Swing components have a repaint() and revalidate() methods. You can make a call to revalidate and then to repaint to refresh that component. – dramzy Oct 08 '14 at 15:18
  • ok I did that and I get an exception java.util.ConcurrentModificationException not sure how to handle concurrency I'm a little new to multithread application development, thanks for your help @dramzy – kknaguib Oct 08 '14 at 15:28
  • I can't really tell what the problem is without seeing your code (Maybe post a new question?). Generally, make sure you only update the GUI on the EDT and any code that is not updating the GUI and might take some time should bo done in a swing worker. You exception might be coming from that main thread and not the EDT though. – dramzy Oct 08 '14 at 15:39