简体   繁体   English

哪个线程运行所有AWT / swing事件处理代码?

[英]Which thread runs all the AWT/swing event handling code?

我是Java的新手,有一个我不理解的毕业生角色面试问题,所以请您告诉我哪个线程及其目的。

Swing UI toolkit is single threaded (in the sense that it is unsafe to call any of the swing libraries from any other thread). Swing UI工具箱是单线程的(从任何其他线程调用任何Swing库都是不安全的)。 All the UI events, both rendering and dispatching them is done by the EDT thread . 所有的UI事件,包括渲染和分派,都由EDT thread

So on clicking at a button on desktop. 因此,单击桌面上的按钮。 The OS gives the notification to EDT which receives the event and then triggers the callback function which was registered for the button click. 操作系统将通知发送给EDT,EDT接收事件,然后触发为单击按钮注册的回调函数。 Moreover from the code, when you do some action (for ex: repaint screen or draw Image). 此外,从代码中,当您执行某些操作时(例如:重画屏幕或绘制图像)。 The EDT delivers the change to the OS and it is rendered on the screen. EDT将更改传送到OS,并将其呈现在屏幕上。 Hence a 2-way interaction. 因此,双向交互。

Because as mentioned Swing UI toolkit is single-threaded. 因为如前所述,Swing UI工具箱是单线程的。 Hence it is advisable to call any of the Swing libraries from EDT only usign System.invokeLater. 因此,建议仅使用System.invokeLater来调用EDT中的任何Swing库。 More info here . 更多信息在这里

You're looking for the Event Dispatch Thread . 您正在寻找Event Dispatch Thread

Knowing about it is pretty.. important. 了解它是非常重要的。 It is vital to understand what thread your code will end up running on - long-running tasks should not be run on the EDT. 至关重要的是要了解什么线程你的代码最终会运行上-长时间运行的任务应该在美国东部时间运行。 Instead, dispatch those tasks on their own thread, then run a callback at the end of the operation to update the GUI using SwingUtilities . 而是将这些任务分派到自己的线程上,然后在操作结束时运行回调以使用SwingUtilities更新GUI。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM