带有 Swing UI 的 Java 线程
在设置线程来启动 MIDI 音序器时遇到一些麻烦后,我决定简单地删除它,尽管它会减慢我的 UI 速度,但我将能够正确使用它。
然而我注意到,即使在播放音序器时,UI 也非常活跃,即使播放大约 500 个音符,UI 也运行得非常好。
现在我知道,在 C# 中,如果您正在做一些密集的事情,建议将其加载到新线程上,因为它将释放 UI。 Java中也是这样的原理吗,真是让我困惑。如果是这样,有人可以解释一下用户界面如何不被阻止吗?
谢谢
编辑:
以下代码实际上播放了序列
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
}
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.
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.
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. Is it the same principle in Java, it's really confused me. If so can someone explain how the UI is not being blocked?
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,这是同一个理论。只有事件线程可以修改 UI,因此如果您在该线程上执行任何操作,那么您就会阻止其他事件在 UI 上工作。
将事件线程视为队列可能更容易:
操作
)如果#3 需要很长时间,那么它可能意味着您的表单将显示为锁定状态。显然这完全取决于你对 long 的定义。一般来说,最好在事件线程之外工作而不是在事件线程上工作。
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.
It may be easier to think about the Event Thread as a queue:
Action
)If #3 takes long, then it may mean that your form will appear locked up. Obviously it completely depends on your definition of long. In general, it's better to work off of the Event Thread rather than on it.
肯定是同一个校长。一般来说,您只想对 UI 线程做最少的工作。如果最终花费了大量时间,可能会导致 UI 无响应,并且您可能会收到“未响应”错误。您希望尽可能保持 UI 线程空闲,以便它可以响应用户交互。
It's definitely the same principal. Generally speaking you want to only do minimal work with the UI thread. If it ends up taking any significant time, it can cause the UI to be unresponsive and you can get a "Not Responding" error. You want to keep the UI thread as free as possible so it can respond to user interaction.
如果您的应用程序有图形用户界面,建议您在新线程上执行昂贵的计算,以防止图形冻结。您可以创建 SwingWorker,或者使用Callable/Future 习惯用法。
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.
是的,你说得对。有关详细信息,请阅读线程和 Swing。
Yes, you're right. Read Threads and Swing for more info.