java - 在 Spring 支持的 java 独立应用程序中将 SwingUtilities.invokeLater 放在哪里?

标签 java multithreading spring swing

我正在为我的 java Swing 应用程序使用 Spring 框架。我以这种方式在 application-context.xml 中将我的 MVC 对象初始化为 spring bean,并使用 @Autowired 进行 DI。

<bean id="model" class="com.Model"/>

<bean id="view" class="com.View"/>

<bean id="controller" class="com.Controller"/>

运行成功,没有任何问题。然而,通过阅读this question ,出于这个原因,我认为我应该将每个 Swing 组件都放在 SwingUtilities.invokerLater() 中。

Some Swing component methods are labelled "thread safe" in the API specification; these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.

所以我的问题是,在哪里/如何将我的东西放入此事件调度线程?目前我的主要方法只是一个衬垫......

ApplicationContext context =
    new ClassPathXmlApplicationContext("application-context.xml");

更新: 我想知道这是否是我应该做的?

SwingUtilities.invokeLater(new Runnable() {
  public void run() {
     ApplicationContext context =
        new ClassPathXmlApplicationContext("application-context.xml");
  }
  context.xxxx
  blahblahblah...
});

最佳答案

要在事件分派(dispatch)线程上运行代码,您可以执行以下操作:

EventQueue.invokeLater(new Runnable() {
    public void run() {
       //your code here
    }
 });

...或等效的:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
       //your code here
    }
 });

您可以在任何需要在事件分派(dispatch)线程上运行代码的位置使用任一方法。只需将代码包装在匿名 Runnable 中即可。

请注意,如果您在匿名 Runnable 实现之外定义了要从其中访问的变量,则需要将它们声明为 final。有关详细信息,请尝试以下操作:

关于java - 在 Spring 支持的 java 独立应用程序中将 SwingUtilities.invokeLater 放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22452426/

相关文章:

java - 为什么我的示例不抛出 ConcurrentModificationException

java - 从 Map 中找出给定值的键的更快方法?

multithreading - 多线程依赖于机器的架构吗?

java - 如何在参数化查询中使用 spring MVC jdbcTempates 传递字符串以删除多行

java - Struts2 中的转换和验证问题

java二叉搜索树寻找第二小的节点

multithreading - 另一个 "Can' t 在未调用 Looper.prepare() 的线程内创建处理程序”主题

java - gui 中新线程的问题

java - 单页应用。模板管理的安全性

java - 配置类 : ClassNotFoundException 的应用程序监听器时出错