Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why add EventQueue.invokeLater?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Why add EventQueue.invokeLater? in view of this problem, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

For example, the following program:

Import java.awt.*

Import javax.swing.*

Public class Test

{

Public static void main (String [] args)

{

EventQueue.invokeLater (new Runnable ()

{

Public void run ()

{

JFrame frame = new JFrame ()

Frame.setSize (400,300)

Frame.setVisible (true)

Frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE)

}

});

}

}

Reason:

Java's GUI is strictly single-threaded.

All GUI related things in java should always go through a single thread. The thread is our legendary "AWT-EventQueue-0". Hence all GUI related actions should necessarily go through the AWT Event thread. If not so you may end up in a deadlock. For small programs, this might never happen. But for a huge java application if you try frame.setVisible (true) kind of thing in main thread, you will soon find yourself searching a new job. What invokeLater () does is to post your Runnable in the AWT thread's event queue. So the code in your run method will be executed in the AWT-Eventqueue thread.

The general idea is that the GUI of java is single-threaded and should be executed with event scheduling threads, which may cause deadlocks if it is not interesting to use event scheduling threads. But in small programs, this phenomenon (deadlock) does not happen; it only happens in large applications!

The answer to the question about why to add EventQueue.invokeLater is shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report