문제

I want to make sure I understand something. Please confirm of this is true or not.

One I declare a thread, and run something inside it - everything from that point on is going to run inside that thread, unless I explicitly create a new thread. No matter how many classes and methods the code passes through - it will stay in the same thread.

For example, let's say I have an application that runs entirely inside one custom JFrame. If I want the entire application to run inside the same thread, I can do this by creating a new thread, and instantiating the new JFrame inside the run() method of that thread.

Will this actually ensure that the entire application will run inside that thread where the JFrame was created, unless I explicitly create a new thread and run something inside that new thread?

This is a general question, but let me talk about Swing specifically for a second:

If I want the entire Swing application to run inside the EDT (which - and please correct me if I'm wrong - is exactly what I need most of the time with Swing), it's enough to use SwingUtilities.invokeLater() once in the main method, like so:

public static void main(String[]args){
    SwingUtilities.invokeLater( new Runnable(){
         JFrame frame = new CustomJFrame(); // where the entire application runs.
    } );
}
도움이 되었습니까?

해결책

One I declare a thread, and run something inside it - everything from that point on is going to run inside that thread, unless I explicitly create a new thread. No matter how many classes and methods the code passes through - it will stay in the same thread.

Correct. In fact even if you create a new thread, current thread execution flow will never be changed. This new thread will start executing some time in the future after you started it, but its flow is independent from the thread that created it.

which - and please correct me if I'm wrong - is exactly what I need most of the time with Swing

You're wrong. You don't want to do everything in the EDT. Any data fetching and manipulation in the EDT will degrade your GUI reponsiveness. Say for example you want to fetch a lot of data from a DB. If you do so in the EDT, your GUI will freeze and the user will not be able to interact with it until you finish getting it (and probably manipulating it).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top