简体   繁体   English

带有Swing UI的Java线程

[英]Java Threads with Swing UI

After having some trouble with setting up a thread to start my MIDI sequencer I decided to simply remove it, although it would slow my UI down I would be able to use it correctly. 设置一个线程来启动我的MIDI音序器后遇到了一些麻烦我决定简单地删除它,虽然它会减慢我的UI速度,但我可以正确使用它。

What I noticed however was that even when playing the Sequencer the UI was very much active, even if it was playing around 500 notes the UI worked perfectly fine. 然而我注意到,即使在播放Sequencer时,UI也非常活跃,即使它播放了大约500个音符,UI也能完美地运行。

Now I know that in C# if you are doing something intensive it is advisable to load it on a new Thread as it will free the UI. 现在我知道在C#中,如果你正在做一些密集的事情,建议将它加载到新的Thread上,因为它将释放UI。 Is it the same principle in Java, it's really confused me. 这是Java中的原理,它让我很困惑。 If so can someone explain how the UI is not being blocked? 如果是这样,有人可以解释UI是如何被阻止的吗?

Thanks 谢谢

Edit: 编辑:

The following code actually plays the Sequence 以下代码实际播放序列

public static boolean Play() {
    if(!_sequencer.isRunning()) {
        try {
            _sequencer.setSequence(_sequence);
            _sequencer.start();

            return true;
        } catch (Exception e) {
            Logger.Add(e.getMessage());
        }
    }
    return false;
    //Already running
}

Yes, it is the same theory. 是的,这是相同的理论。 Only the Event Thread can modify the UI, and thus if you are doing anything on that thread, then you are preventing other events from working on the UI. 只有事件线程可以修改UI,因此如果您在该线程上执行任何操作,那么您将阻止其他事件在UI上工作。

It may be easier to think about the Event Thread as a queue: 将事件线程视为队列可能更容易:

  1. Show Form 显示表格
  2. Click Button 单击按钮
  3. Do your work ( Action ) 做你的工作( Action
  4. Reset focus of Button 重置Button的焦点
  5. Update Progress Bar 更新进度条
  6. Et cetera 等等

If #3 takes long, then it may mean that your form will appear locked up. 如果#3需要很长时间,那么这可能意味着您的表单会显示为已锁定。 Obviously it completely depends on your definition of long. 显然它完全取决于你对long的定义。 In general, it's better to work off of the Event Thread rather than on it. 一般来说,最好使用Event Thread而不是它。

It's definitely the same principal. 这绝对是同一个校长。 Generally speaking you want to only do minimal work with the UI thread. 一般来说,您只希望使用UI线程进行最少的工作。 If it ends up taking any significant time, it can cause the UI to be unresponsive and you can get a "Not Responding" error. 如果它最终花费了大量时间,则可能导致UI无响应,并且您可能会收到“无响应”错误。 You want to keep the UI thread as free as possible so it can respond to user interaction. 您希望尽可能保持UI线程免费,以便它可以响应用户交互。

If your application has a graphical user interface, it's advised that you perform expensive calculations on a new Thread to keep your graphics from freezing. 如果您的应用程序具有图形用户界面,则建议您对新线程执行昂贵的计算以防止图形冻结。 You can either create a SwingWorker , or use the Callable/Future idiom. 您可以创建SwingWorker ,也可以使用Callable / Future习惯用法。


Yes, you're right. 你是对的。 Read Threads and Swing for more info. 阅读线程和Swing了解更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM