本文介绍了invokeLater 的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很确定所有这些方法都行得通,但我很想知道哪种方法最好.

Pretty sure all of these approaches will work, but I'd appreciate opinions on which is the best.

为了论证起见,请考虑(不幸的)场景,其中 UI 更改代码和相当密集(平均 500 毫秒)的逻辑代码混合且不可分割.所有不断变化的 ui 组件都在一个面板上.

Consider for argument's sake the (unfortunate) scenario where you have UI changing code and reasonably intensive (average 500ms) logic code mixed and inseparable. all of the changing ui components are on the one panel.

01 new Thread(){
02  public void run(){
03
04  for (int i = 0; i < 100; i++){
05      // some processing
06      doSomething();
07      // update some ui components
08      panel.doSomeUi();
09  }
10
11  panel.revalidate();
12  panel.repaint();
13
14 }}.start();

您会选择以下 3 种方法中的哪一种?为什么?

Which of the following 3 approaches would you choose and why?

  1. 将所有代码包装在 invokeLater 中
  2. 在 doSomeUi() 中调用 invokeLater,然后再次进行重新验证/重绘
  3. 仅在最后使用 invokeLater 进行重新验证/重绘

我的:

选项 1 会在所有处理发生时挂起事件处理线程 (EPT)

option 1 would hang the Event Processing Thread (EPT) while all of the processing occurs

选项 2 会考虑开销,因为要创建许多新的可运行对象,并且在特殊情况下,如果组件需要某些后续 ui 更改有效,则可能会导致 ui 在半完成状态下更新

option 2 would have overhead considerations with many new runnables being created and in special cases may cause the ui to update in a half complete state if components need some of the subsequent ui changes to be valid

选项 3 将是最有效的,但可能存在一些线程安全问题

option 3 would be the most efficient but may have some thread safety issues

热衷于听取其他意见.

推荐答案

doSomeUi() some 应该包含在 invokeLater() and 应该触发任何必要的重绘/重绘——SwingUI 线程将在您继续计算时绘制.

The doSomeUi () some should be wrapped in an invokeLater () and should trigger whatever repaint/redrawing is necessary -- the Swing UI thread will paint while you keep computing.

在现代 VM 上创建大量短期 Runnable 的开销很小,应该不会成为问题.

The overhead of creating a lot of short-lived Runnable's will be tiny on a modern VM, and shouldn't be an issue.

所以,选项 2(建议修改)应该是它.在编写多线程代码时,缓慢而正确的总是比快速和随机错误要好.

So, option 2 (with suggested modification) should be it. When writing multi-threaded code, slow and correct is always better than fast and randomly buggy.

这篇关于invokeLater 的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 12:06