java – JOptionPane.showMessageDialog线程安全吗?

JOptionPane.showMessageDialog应该是一个有用的实用程序,用于获取用户反馈,因为它会在您等待时阻止当前线程.

因此我希望它是线程安全的,你不需要在invokeLater或invokeAndWait中包装调用.

是这样的吗?

最佳答案
取自javax.swing包描述:

Swing’s Threading Policy

In general Swing is not thread safe. All Swing components and related classes, unless otherwise documented, must be accessed on the event dispatching thread. Typical Swing applications do processing in response to an event generated from a user gesture. For example, clicking on a JButton notifies all ActionListeners added to the JButton. As all events generated from a user gesture are dispatched on the event dispatching thread, most developers are not impacted by the restriction.

Where the impact lies, however, is in constructing and showing a Swing application. Calls to an application’s main method, or methods in Applet, are not invoked on the event dispatching thread. As such, care must be taken to transfer control to the event dispatching thread when constructing and showing an application or applet. The preferred way to transfer control and begin working with Swing is to use invokeLater. The invokeLater method schedules a Runnable to be processed on the event dispatching thread.

JOptionPane没有记录它是线程安全的,所以你必须使用invokeLater().

转载注明原文:java – JOptionPane.showMessageDialog线程安全吗? - 代码日志