Documentation

The Java™ Tutorials
Hide TOC
The Event Dispatch Thread事件调度线程
Trail: Creating a GUI With Swing
Lesson: Concurrency in Swing

The Event Dispatch Thread事件调度线程

Swing event handling code runs on a special thread known as the event dispatch thread. Swing事件处理代码运行在一个称为事件分派线程的特殊线程上。Most code that invokes Swing methods also runs on this thread. 大多数调用Swing方法的代码也在这个线程上运行。This is necessary because most Swing object methods are not "thread safe": invoking them from multiple threads risks thread interference or memory consistency errors. 这是必要的,因为大多数Swing对象方法都不是“线程安全的”:从多个线程调用它们有线程干扰内存一致性错误的风险。Some Swing component methods are labelled "thread safe" in the API specification; these can be safely invoked from any thread. 一些Swing组件方法在API规范中被标记为“线程安全”;这些可以从任何线程安全调用。All other Swing component methods must be invoked from the event dispatch thread. 所有其他Swing组件方法都必须从事件分派线程调用。Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.忽略此规则的程序在大多数情况下都可以正常运行,但会出现难以重现的不可预知错误。

It's useful to think of the code running on the event dispatch thread as a series of short tasks. 将事件分派线程上运行的代码看作一系列短任务是很有用的。Most tasks are invocations of event-handling methods, such as ActionListener.actionPerformed. 大多数任务都是事件处理方法的调用,例如ActionListener.actionPerformedOther tasks can be scheduled by application code, using invokeLater or invokeAndWait. 其他任务可以使用invokeLaterinvokeAndWait由应用程序代码调度。Tasks on the event dispatch thread must finish quickly; if they don't, unhandled events back up and the user interface becomes unresponsive.事件分派线程上的任务必须快速完成;如果不这样做,未处理的事件会备份,用户界面将变得无响应。

If you need to determine whether your code is running on the event dispatch thread, invoke javax.swing.SwingUtilities.isEventDispatchThread.如果需要确定代码是否在事件分派线程上运行,请调用javax.swing.SwingUtilities.isEventDispatchThread


Previous page: Initial Threads
Next page: Worker Threads and SwingWorker