【发布时间】:2016-04-12 16:31:36
【问题描述】:
我目前正在使用其他人编写的线程控制类。它用于 java swing 应用程序。我有两种方法,但我很困惑为什么我会从两种方法中得到不同的行为。根据我对事件调度程序线程和 Swing 的了解和阅读,以下两种方法应该没有区别。显然,这不是真的。
//If this is the AWT Event Processing thread then run the code immediately,
//otherwise schedule it for later processing
public static void runWithEventThread(Runnable r)
{
if (EventQueue.isDispatchThread())
{
r.run();
}
else
{
EventQueue.invokeLater(r);
}
}
//Schedule the runnable for later processing by the AWT Event Queue
public static void runLaterWithEventThread(Runnable r)
{
EventQueue.invokeLater(r);
}
在更新 GUI(新按钮/重新绘制)时使用 runWithEventThread() 显示弹出窗口时,我发现 GUI 有时会混乱。但是,当使用 runLaterWithEventThread() 时,一切都很好,没有问题。
唯一的问题是,在使用 runLaterWithEventThread() 时,我发现当我有多个弹出窗口会一个接一个地显示时(单击确定后),所有弹出窗口都会同时显示。
据我了解,这两种方法都应该做同样的事情。有人可以解释一下发生了什么
【问题讨论】:
-
Re,“GUI 有时会搞砸” “搞砸”是什么意思?另外,您传递的任务需要多长时间才能运行?
-
我基本上是在改变 JList 项目的颜色。作为 JList 的一部分的混乱被弹出屏幕的扭曲图像覆盖。类似于程序崩溃并且您将屏幕最小化,但有时会保留程序的扭曲图像。我传递给 run 的任务首先是更新 Jlist,然后是弹出窗口。
标签: java multithreading swing event-dispatch-thread invokelater