madzohan
madzohan

Reputation: 11808

java multithreading split calculation between a given number of threads

I have simple method that calculates pow of each number in array and returns these numbers in new array ... My question is how I can split this calculation to given number of threads and thereby speed up the execution of the method

public class ExtClass{
    public static long pow(long a, int b) {
        if (b == 0)        return 1;
        if (b == 1)        return a;
        if ((b & 1) == 0)  return     pow (a * a, b/2);
        else               return a * pow(a * a, b/2);

    }

    public static long[] val(long[] a, int p) {
        long[] result_array = new long[a.length];

        for (int i = 0; i < a.length - 1; i++) {
            result_array[i] = pow(a[i], p);
        }

        return result_array;
    }

P.S. I'm totally noob in java and need your help plz =)

Upvotes: 0

Views: 422

Answers (1)

Yogesh_D
Yogesh_D

Reputation: 18764

On a high level:

  1. You create a callable class, that has the implementation of the, pow method.
  2. You create a executor based on the max available processors that you seemed to have figured out.
  3. You create the callables and submit them to the executor.
  4. Using the Future's returned you collate the results

These links should get you started: https://blogs.oracle.com/CoreJavaTechTips/entry/get_netbeans_6 http://www.journaldev.com/1090/java-callable-future-example

Upvotes: 2

Related Questions