AsyncTask is very useful to synchronized between UI thread and other threads in Android. So I have read its source code and tried porting to java classic (JDK) but no success because some classes don't exist in java (Message, Handler..).
I would like to create a class with some useful functions like AsyncTask (that can synchronized between main thread and other threads) :
doInBackground(Params... params)
onProgressUpdate(Progress... values)
onPostExecute(Result result)
publishProgress(Progress... values)
onPreExecute()
onCancelled()
Is there any way to try that?
There are a few threading rules that must be followed for this class to work properly: The AsyncTask class must be loaded on the UI thread. This is done automatically as of Build.
Android AsyncTask is an abstract class provided by Android which gives us the liberty to perform heavy tasks in the background and keep the UI thread light thus making the application more responsive. Android application runs on a single thread when launched.
Thread can be triggered from any thread, main(UI) or background; but AsyncTask must be triggered from main thread. Also on lower API of Android(not sure, maybe API level < 11), one instance of AsyncTask can be executed only once. Long task in general.
In newer Android versions, 5 threads are create by default, and the ThreadPoolExecutor will attempt to run the AsyncTask s on these 5 threads. If you create more than 5 AsyncTask s, it may either queue them or create new threads (but only up to 128).
Agreed that SwingWorker
is the most direct analog to AsyncTask
If you aren't using Swing, another option is a ThreadPoolExecutor
: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html
Here's an article demonstrating using ThreadPoolExecutor
to spawn multiple background threads: http://www.javacodegeeks.com/2013/01/java-thread-pool-example-using-executors-and-threadpoolexecutor.html
Spawning a single background thread that runs and completes without progress update (which is also a common use of AsyncTask
in Android) can be as simple as:
Executors.newSingleThreadExecutor().execute(new Runnable() {
@Override
public void run() {
// do stuff in background
}
});
1. AsyncTask
is specially developed for android to sync the UI thread and the Non-UI thread, also known as Painless threading.....
2. There is an alternative of AsyncTask in Java named as SwingWorker
.
See this link for a nice basic tutorial:
http://kodejava.org/how-do-i-use-swingworker-to-perform-background-tasks/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With