开发者

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.

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
}


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:

  1. Show Form
  2. Click Button
  3. Do your work (Action)
  4. Reset focus of Button
  5. Update Progress Bar
  6. Et cetera

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.


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.


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.



Yes, you're right. Read Threads and Swing for more info.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜