简体   繁体   中英

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

PS I'm totally noob in java and need your help plz =)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM