Differences between Java SwingWorker and Android AsyncTask

I compared the differences between Swing classes SwingWorker and Android AsyncTask . While Android has a Main thread / UI Theme and then a background thread is generated (using AsyncTask ), SwingWorker has three threads that are involved -

  • Current stream
  • Work flow
  • Dispatch event theme.

And then I also came across a statement (in the docs) -

Often the current thread is Thread Dispatch Thread.

Now what does that mean?

Does this mean that Swing also has only one thread - the main topic and even events are accepted in one thread OR Difference in different JVM implementations?

+6
source share
1 answer

This is true only for Swing, which bears some resemblance to programming on the Android UI, but in reality it is not the same.

A bit of context

EDT (Thread Dispatch Thread) is a Swing thread designed to handle user interface events (mouse and keyboard input, events on controls, display of the user interface, etc.). This is an Event Loop model similar to what is done on Android.

The fact that event listeners in Swing run on EDT is the main reason for freezing user interfaces in Swing applications: developers do not understand how the multi-threaded model often puts long code in listeners, which blocks EDT and, therefore, the graphical interface.

SwingWorker was introduced to better guide developers in separating user interface updates from years of background code. It generates a dedicated background thread for processing I / O (or a long-term task) in doInBackground and performs user interface updates in the done and process methods. Although these 3 methods guarantee in which thread they will be executed, all other methods are executed in the current thread.

What is meant by the sentence you quoted

The whole reason SwingWorker exists is to properly initiate a long process from the GUI without blocking the GUI.

Often he will respond to user input (for example, pressing a button). Since user input reactions (implemented as Listeners) are always executed in the EDT using the Swing framework, unless you explicitly call execute or get from another thread, it will be executed in the EDT.

By the way, execute is "fire and forget" and is a typical use case (call it a listener). get , on the other hand, is not suitable for calling from a listener (it would defeat the SwingWorker target, if necessary, call it in your threads)!

+5
source

Source: https://habr.com/ru/post/979615/


All Articles