Best practice regarding number of threads in GUI applications

后端 未结 9 1305
谎友^
谎友^ 2021-01-19 16:43

In the past I\'ve worked with a number of programmers who have worked exclusively writing GUI applications.

And I\'ve been given the impression that they have almost

9条回答
  •  借酒劲吻你
    2021-01-19 17:29

    Generally speaking, GUI frameworks aren't thread safe. For things like Swing(Java's GUI API), only one thread can be updating the UI (or bad things can happen). Only one thread handles dispatching events. If you have multiple threads updating the screen, you can get some ugly flicker and incorrect drawing.

    That doesn't mean the application needs to be single threaded, however. There are certainly circumstances when you don't want this to be the case. If you click on a button that calculates pi to 1000 digits, you don't want the UI to be locked up and the button to be depressed for the next couple of days. This is when things like SwingWorker come in handy. It has two parts a doInBackground() which runs in a seperate thread and a done() that gets called by the thread that handles updating the UI sometime after the doInBackground thread has finished. This allows events to be handled quickly, or events that would take a long time to process in the background, while still having the single thread updating the screen.

提交回复
热议问题