user2830310
user2830310

Reputation: 21

how to run two separate asynchronous tasks run separately?

In my application I have two button clicks and in both button clicks there are two different Asynchronous tasks are running ,and my problem is when i click button 1 and first asynchronous task is running mean while its running i clicked second button and second asynchronous task also started but in background till the first asynchronous task is completed the second asynchronous task is not starting ?

public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
if(position==1)
           {

              Asynchronoustask1();

           }

            if(position==2)
            {

              Asynchronoustask2();
            }
}

Upvotes: 2

Views: 124

Answers (3)

Rajith Rajan
Rajith Rajan

Reputation: 121

Asynchronous task always run in background.It will not disturb the any process.Might be your first Asynchronous task holding some resources and that one also using for second one.So its waiting for the resource.

Please have look @ your code carefully or paste your code..

Upvotes: 0

Amulya Khare
Amulya Khare

Reputation: 7708

If your implementation for AsyncTask is correct, then the possible reason for this behaviour is because the default executor for AsyncTasks is SERIAL_EXECUTOR.

To run multiple AsyncTask instances in parallel (not serially.. no one after other). execute them as follows:

if (Build.VERSION.SDK_INT >= 11) {
    outstandingTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
    outstandingTask.execute();
}

From the documentation:

When first introduced, AsyncTask were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent. Executor, Object[]) with THREAD_POOL_EXECUTOR.

Upvotes: 5

Viswanath Lekshmanan
Viswanath Lekshmanan

Reputation: 10083

There are multiple Options to run asyncrhonously Either you can use two AsyncTask which contains a method called doInBackground() for your use. Or simple you can use two threads.

Eg: Thread

Thread thread = new Thread()
{
@Override
public void run() {
    try {
        while(true) {
           // your code
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
};

thread.start();

If you want any delay Use Handler.

Or

You need to do any UI Operations you should use RunOnUIThread()

Upvotes: 0

Related Questions