SwingUtilities.invokeLater 有什么作用? [英] What does SwingUtilities.invokeLater do?

查看:28
本文介绍了SwingUtilities.invokeLater 有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SwingUtilities.invokeLater 有什么作用?它只是在其 run 方法中延迟了代码块的执行吗?在 invokeLater 函数中调用一个动作或在我们想要执行的线程的末尾简单地调用它有什么区别?任何人都可以帮助我了解 invokeLater 函数的真正作用吗?

What does SwingUtilities.invokeLater do? Is it just delaying the execution of a block of codes inside its run method? What is the difference between calling an action within the invokeLater function or simply calling it at the end of the thread we want to be executed? Can anyone help me with what really does the invokeLater function do?

推荐答案

正如其他答案所说,它在 AWT 事件调度线程上执行您的 Runnable.但是你为什么要这样做呢?因为 Swing 数据结构不是线程安全的,所以为了向程序员提供一种易于实现的方法来防止对它们的并发访问,Swing 设计者制定了访问它们的所有代码必须在同一线程上运行的规则.对于事件处理和显示维护代码,这会自动发生,但是如果您已经启动了一个长时间运行的操作——当然是在一个新线程上——您如何发出它的进度或完成的信号?您必须修改 Swing 控件,并且必须从事件调度线程中进行.因此invokeLater.

As other answers have said, it executes your Runnable on the AWT event-dispatching thread. But why would you want to do that? Because the Swing data structures aren't thread-safe, so to provide programmers with an easily-achievable way of preventing concurrent access to them, the Swing designers laid down the rule that all code that accesses them must run on the same thread. That happens automatically for event-handling and display maintenance code, but if you've initiated a long-running action - on a new thread, of course - how can you signal its progress or completion? You have to modify a Swing control, and you have to do it from the event-dispatching thread. Hence invokeLater.

这篇关于SwingUtilities.invokeLater 有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆