1

在准备考试时,我偶然发现了一些对我来说不是很清楚的 java 图形行。所以我开始浏览并检查其他一些程序,它们没有那些行。

例子:

public static void main(String[] args){
  SwingUtilities.invokeLater(new Runnable(){//unknown
  public void run(){                        //lines
  JPanel panel = new DrawingPanel();
  ...
}

现在我知道 Runnable 和 run 必须处理线程,但我不知道这两行为什么以及如何工作

4

2 回答 2

1

Swing objects can only be accessed from the Swing thread that runs in closed loop handling repaints, GUI events and so on. When you application starts, it starts in an ordinary thread (not a Swing thread). The lines that look strange to you use SwingUtilities to execute DrawingPanel constructor and probably more code in the Swing thread.

The code that instantiates the first GUI frame directly from the main thread may also work in practice if it is really the first method ever called (as expected). However it is "fundamentally wrong" approach that may not work later under different machine, if differently called and the like.

于 2013-08-25T11:28:36.237 回答
1

Swing 是一个单线程框架。与 UI 的所有交互和更新都应在事件调度线程的上下文中执行。

Java 不保证main在 EDT 中执行(我相信他们通常称其为主线程)。因此,您需要确保您的任何 UI 代码首先同步到事件调度线程。

SwingUtilities.invokeLater, 代表EventQueue.invokeLater. 这基本上将Runnable实例发布到由事件调度线程处理的事件队列中。

在将来的某个时间,Runnable从队列中弹出并run在 EDT 中执行该方法

有关更多详细信息,请参阅初始线程

您还可以查看Swing中的单线程规则、Swing UI 的事件调度线程规则以获取更多信息

于 2013-08-25T11:31:40.343 回答