Java AWT Threads

妖精的绣舞 提交于 2019-11-28 02:04:23

Swing is not thread safe, so, if you are tryng to update a UI in the same thread you will have the "application freeze" behavior. To solve this, you need to delegate the process of update the UI to another thread. This is made using SwingUtilities.invokeLater (Java 5 and prior) method and/or the SwingWorker class (since Java 6).

Some links:

Google search: https://www.google.com.br/search?q=swing+thread+safe

In support of davidbuzatto:

No, I think you miss under stood what InvokeLater does. InvokeLater ensures that the runnable is executed ON the ETD. So basically, from what I can read, you've gone an put your long running, Event Blocking code right back in the ETD. Only use InvokeLater when you want to update the UI, use Threads or SwingWorker when you want to actually do processing

void processEvents() throws IOException, InterruptedException
    {
        System.out.println("Entered processEvents");

        // PLEASE ETD, PUT THIS AT THE END OF THE QUEUE AND EXECUTE
        // SO I RUN WITHIN YOUR CONTEXT
        SwingUtilities.invokeLater(new Runnable() {
            public void run()
            {

                // NOW RUNNING BACK ON THE ETD
                System.out.println("Entered run");
                list.add("test2");
                list.repaint();

                // NOW BLOCK THE ETD, SO NO MORE REPAINTS OR UPDATES WILL EVER
                // OCCUR
                while(true)
                { 
                    WatchKey key;           
                    try
                    {
                        key = ws.take();
                    }
                    catch (InterruptedException x)
                    {
                        return;
                    }

Sorry for the caps, but I wanted the comments to standout.

1. Swing is Not Thread safe, but some methods like repaint(), setText() are Tread Safe.

2. The main() method in Swing is Not Long Lived. It schedules the construction of GUI in the Event Dispactcher Thread and then quits. Now its the responsibility of the EDT to handle the GUI.

3. You must keep your Non-UI work on your Non-UI thread, out off the GUI thread, ie EDT.

4. Your main() method should only do the work of making the JFrame visible, using EventQueue.invokeLater.

Eg:

    public static void main(String[] args){

       EventQueue.invokeLater(new Runnable(){

       public void run(){

       myFrame.setVisible(true);
     }
  }
}

5 SwingWorker is provided by Java to Synchronize the Work Output of the Non-UI thread on the GUI thread.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!