How does the event dispatch thread work?

前端 未结 4 668

With the help of people on stackoverflow I was able to get the following working code of a simple GUI countdown (which just displays a window counting down seconds). My main

4条回答
  •  萌比男神i
    2020-11-30 09:54

    What is the EDT?

    It's a hacky workaround around the great many concurrency issues that the Swing API has ;)

    Seriously, a lot of Swing components are not "thread safe" (some famous programmers went as far as calling Swing "thread hostile"). By having a unique thread where all updates are made to this thread-hostile components you're dodging a lot of potential concurrency issues. In addition to that, you're also guaranteed that it shall run the Runnable that you pass through it using invokeLater in a sequential order.

    Then some nitpicking:

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                showGUI();
                counter.start();
            }
        });
    }
    

    And then:

    In the main method we also start the counter and the counter (by construction) is executed in another thread (so it is not in the event dispatching thread). Right?

    You don't really start the counter in the main method. You start the counter in the run() method of the anonymous Runnable that is executed on the EDT. So you really start the counter Thread from the EDT, not the main method. Then, because it's a separate Thread, it is not run on the EDT. But the counter definitely is started on the EDT, not in the Thread executing the main(...) method.

    It's nitpicking but still important seen the question I think.

提交回复
热议问题