Northumber
Northumber

Reputation: 315

How to multi-thread calculation Android

I want to use multi-threading for two different calculation. I have an AsyncTask, which inside have the function "doInBackground". In this function I want to do more calculation exploiting multiple cores. I tried to use IntentService, but I do not know how it works. This is the code of main activity:

@Override
public String doInBackground(Void... params) {
   long startTime = System.currentTimeMillis();
   Intent multi_pi = new Intent(
                         getApplicationContext(),
                         multi_pi.class
                    );
   startActivity(multi_pi);
   long endTime = System.currentTimeMillis();
   long total_time = endTime - startTime;
   String time = Long.toString(total_time);
   return time;
}

This is the code of the first calculation:

public class multi_pi extends IntentService {
   public multi_pi(String pi_1) {
      super(pi_1);
   }

   @Override
   protected void onHandleIntent(Intent pi_1) {
    //first calculation
   }
}

Is there another solution to do this?

Upvotes: 1

Views: 297

Answers (1)

eleven
eleven

Reputation: 6857

First of all you can't exploit multiple cores. Only the system decides whether to use one core or several to solve particular task or tasks.

But you can give a gentle hint to the system that you need to perform several tasks concurrently: just create two or more threads.

new Thread(new Runnable() {
    @Override public void run() {
        //calculations #1
    }
}).start();
new Thread(new Runnable() {
    @Override public void run() {
        //calculations #2
    }
}).start();

That's all.

Classes like AsyncTask, IntentService and Service have particular aims. If just need to run two threads there is no need to use AsyncTask or IntentService at all.

Upvotes: 1

Related Questions