How can port AsyncTask from Android to java?-ThrowExceptions

Exception or error:

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?

How to solve:

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/

###

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
  }
});

###

I use the Observer design pattern for a similar situation. After spawning a background thread, the main thread goes into sleep mode. When the background thread finishes the asynchronous task, it wakes up the main thread with a callback message. This essentially removes a block on a synchronization object that was waiting for the callback.

Leave a Reply

Your email address will not be published. Required fields are marked *